Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Linq

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    
    static List<Item> cart = new List<Item>();
    
  public class Product
  {
    public string Id {  get; set;  }
    
    public string Name { get; set; }
    
    public double Price { get; set; }

    public string Photo { get; set; }
  }

  public class Item
  {
    public Product Product { get; set; }

    public int Quantity { get; set; }

  }

  public class ProductModel
  {

    private List <Product> products;	// = new List<Product>();
    
    public ProductModel ()
    {

      this.products = new List <Product> ()
      {
    	    new Product { Id = "p01", Name = "Name 1", Price = 5, Photo = "thumb1.gif"}, 
        	new Product { Id = "p02", Name = "Name 2", Price = 5, Photo = "thumb2.gif"}, 
            new Product	{ Id = "p03", Name = "Name 3", Price = 10, Photo = "thumb3.gif"}
      };  
           
    }

    public List <Product> findAll ()
    {
      return this.products;
    }
    
    public Product find(string id){
        return this.products.Single(p => p.Id.Equals(id));
    }

  }


  public static void Main ()
  {
    List <Product> product;
    string input;
    
    // cart = new List<Item>();

    Console.WriteLine ("Hello World !");

    ProductModel pm = new ProductModel ();

    product = pm.findAll ();


    foreach (Product item in product)
    {

      Console.WriteLine (item.Id + " : " + item.Name + " : " + item.Price + " : " + item.Photo);

    }

    for (int i = 0; i < 1000; i++)
      {
	    // Console.Write (i);

	if (i == 1500)
	   {
	    throw new ApplicationException ("Application Exception");
	   } 
     }
     
      Console.WriteLine("\n Upisi id");
      input = Console.ReadLine();
      Console.WriteLine("Upisani: {0}", input);
      
      Console.WriteLine(pm.find(input).Id + " : " + pm.find(input).Name + " : " + pm.find(input).Price + " : " + pm.find(input).Photo);
      
       int index = 0;

     while(true){
          Console.WriteLine("Sto zelite kupiti");
          input = Console.ReadLine();
          // Console.WriteLine("Broj proizvoda u kosarici:" + cart.Count()); 
            
             if(isExist(input) == -1){
                 cart.Add(new Item{ Product = pm.find(input),  Quantity = 1});
             }
             else{
                 index = isExist(input);
                 /* if(input == "p01")
                  index = 0;
                 else if(input == "p02")
                  index = 1;
                 else if(input == "p03")
                  index = 2; */

                 cart[index].Quantity++; 
             } 
             
             foreach(Item item in cart){
                 Console.WriteLine(item.Product.Id + ": " + item.Quantity);
             }
             
             // Cart kosarica = cart.findAll();
                 
             Console.WriteLine("Broj proizvoda u kosarici:" + cart.Count()); 
     } 
  }
   
   private static int isExist(string id){
       for(int i=0; i<cart.Count; i++){
           if(cart[i].Product.Id.Equals(id)){
               return i;
           }
       }
       
       return -1;
   }
}

Blockchain

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;

class Block
{
    public int Index { get; set; }
    public DateTime TimeStamp { get; set; }
    public string PreviousHash { get; set; }
    public string Hash { get; set; }
    public string Data { get; set; }

    public string CalculateHash()
    {
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes($"{TimeStamp}-{PreviousHash}-{Data}"));

            StringBuilder builder = new StringBuilder();
            foreach (var t in bytes)
            {
                builder.Append(t.ToString("x2"));
            }

            return builder.ToString();
        }
    }

    public override string ToString()
    {
        StringBuilder output = new StringBuilder();
        output.AppendLine("=============================================================================");
        output.AppendLine($"Block Index: {Index}");
        output.AppendLine($"Added:       {TimeStamp:HH:mm:ss}");
        output.AppendLine($"Prev Hash:   {PreviousHash}");
        output.AppendLine($"This Hash:   {Hash}");
        output.AppendLine($"Transaction: {Data}");
        output.AppendLine("=============================================================================");

        return output.ToString();
    }
}

class BlockChain
{
    public IList<Block> Chain { private set; get; }

    public BlockChain()
    {
        Chain = new List<Block>();
    }

    public void CreateGenisisBlock()
    {
        var genesisBlock = new Block
        {
            Index = 0,
            TimeStamp =  DateTime.Now,
            PreviousHash = null,
            Data = "Genesis Block"
        };
        genesisBlock.Hash = genesisBlock.CalculateHash();

        Chain.Add(genesisBlock);
    }

    public void AddBlock(Block blockToAdd)
    {
        Block latestBlock = LastBlock;
        
        blockToAdd.TimeStamp = DateTime.Now;
        blockToAdd.Index = latestBlock.Index + 1;
        blockToAdd.PreviousHash = latestBlock.Hash;
        blockToAdd.Hash = blockToAdd.CalculateHash();
        
        Chain.Add(blockToAdd);
    }

    public Block LastBlock
    {
        get { return Chain.Last(); }
    }

    public bool IsValid
    {
        get
        {
            foreach (var block in Chain)
            {
                if (block.PreviousHash == null)
                    continue;

                var previousBlock = Chain[block.Index - 1];

                if (block.Hash != block.CalculateHash())
                {
                    Console.WriteLine($"Error in Block Index {block.Index}");
                    return false;
                }

                if (block.PreviousHash != previousBlock.Hash)
                {
                    Console.WriteLine($"Error in Block Index {block.Index}");
                    return false;
                }
            }

            return true;
        }
    }

    public void Print()
    {
        Chain.ToList().ForEach(Console.WriteLine);
    }
}    

class Program
{
    static void Main()
    {
        // create block chain and genesis block
        BlockChain myCurrency = new BlockChain();
        myCurrency.CreateGenisisBlock();

        myCurrency.AddBlock(new Block()
        {
            Data = "+10 Goldtaler von Mike an Lara"
        });

        myCurrency.AddBlock(new Block()
        {
            Data = "+5 Goldtaler von Sue an Lara"
        });

        myCurrency.AddBlock(new Block()
        {
            Data = "+15 Goldtaler von Alice an Lara"
        });

        // print current block chain and verify it
        myCurrency.Print();
        Console.WriteLine((myCurrency.IsValid ? "Blockchain OK" : "!!! Blockchain corrupted !!!") + System.Environment.NewLine + System.Environment.NewLine);


        // attacker tries to modify block chain
        myCurrency.Chain[1].Data = "+5 Goldtaler von Sue an Rob";
        myCurrency.Print();
        Console.WriteLine((myCurrency.IsValid ? "Blockchain OK" : "!!! Blockchain corrupted !!!") + System.Environment.NewLine + System.Environment.NewLine);


        // more clever attacker recalculates also hash
        myCurrency.Chain[1].Data = "+5 Goldtaler von Sue an Rob";
        myCurrency.Chain[1].Hash = myCurrency.Chain[1].CalculateHash();
        myCurrency.Print();
        Console.WriteLine((myCurrency.IsValid ? "Blockchain OK" : "!!! Blockchain corrupted !!!") + System.Environment.NewLine + System.Environment.NewLine);

        Console.ReadKey();
    }    
}

luii

using System;

namespace RectangleApplication {

   class Rectangle {
      //member variables
      private double length;
      private double width;
      
      public void Acceptdetails() {
         Console.WriteLine("Enter Length: ");
         length = Convert.ToDouble(Console.ReadLine());
         Console.WriteLine("Enter Width: ");
         width = Convert.ToDouble(Console.ReadLine());
      }
      
      public double GetArea() {
         return length * width;
      }
      
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }//end class Rectangle
   
   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine();
      }
   }
}

C# - File I/O

using System.IO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
  
    public interface IHierarchical<TElement, TParent>
        where TElement : IHierarchical<TElement, TParent>
        where TParent : TElement
    {
        
        /**
         * @return true if this element has a parent, or false otherwise
         */
        bool HasParent();
        
        /**
         * @return the parent of this element, or null if this represents the top of a hierarchy
         */
        TParent GetParent();

    }
	public interface IHierarchy<TElement, TParent> 
        where TElement : IHierarchical<TElement, TParent>
        where TParent : TElement
    {
        /**
         * Adds a given element to the hierarchy.
         * <p>
         * If the given element is already present in the hierarchy,
         * do not add it and return false
         * <p>
         * If the given element has a parent and the parent is not part of the hierarchy,
         * add the parent and then add the given element
         * <p>
         * If the given element has no parent but is a Parent itself,
         * add it to the hierarchy
         * <p>
         * If the given element has no parent and is not a Parent itself,
         * do not add it and return false
         *
         * @param element the element to add to the hierarchy
         * @return true if the element was added successfully, false otherwise
         */
        bool Add(TElement element);
        
        /**
         * @param element the element to search for
         * @return true if the element has been added to the hierarchy, false otherwise
         */
        bool Has(TElement element);

        /**
         * @return all elements in the hierarchy,
         * or an empty set if no elements have been added to the hierarchy
         */
        ISet<TElement> GetElements();

        /**
         * @return all parent elements in the hierarchy,
         * or an empty set if no parents have been added to the hierarchy
         */
        ISet<TParent> GetParents();

        /**
         * @param parent the parent whose children need to be returned
         * @return all elements in the hierarchy that have the given parent as a direct parent,
         * or an empty set if the parent is not present in the hierarchy or if there are no children
         * for the given parent
         */
        ISet<TElement> GetChildren(TParent parent);

        /**
         * @return a map in which the keys represent the parent elements in the hierarchy,
         * and the each value is a set of the direct children of the associate parent, or an
         * empty map if the hierarchy is empty.
         */
        IDictionary<TParent, ISet<TElement>> GetHierarchy();

        /**
         * @param element
         * @return the parent chain of the given element, starting with its direct parent,
         * then its parent's parent, etc, or an empty list if the given element has no parent
         * or if its parent is not in the hierarchy
         */
        IList<TParent> GetParentChain(TElement element);
    }

/******************************************************************************************************************************************
******************************************************************************************************************************************/

	public interface ICapitalist : IHierarchical<ICapitalist, FatCat>
    {
        //List<ICapitalist> IMasterList { get; set; }
        //Stack ILog { get; set; }
        /**
         * @return the name of the capitalist
         */
        string GetName();

        /**
         * @return the salary of the capitalist, in dollars
         */
        int GetSalary();
    }
	
    public class WageSlave : ICapitalist
    {
        string Name { get; set; }
        int Salary { get; set; }
        FatCat Owner { get; set; }

        public WageSlave(string name, int salary) {
            Name = name;
            Salary = salary;
        }

        public WageSlave(String name, int salary, FatCat owner) {
            Name = name;
            Salary = salary;
            Owner = owner;
        }

        /**
         * @return the name of the capitalist
         */
        public String GetName() {
            return Name;
        }

        /**
         * @return the salary of the capitalist, in dollars
         */
        public int GetSalary() {
            return Salary;
        }

        /**
         * @return true if this element has a parent, or false otherwise
         */
        public bool HasParent() {
            return Owner != null ? true : false;
        }

        /**
         * @return the parent of this element, or null if this represents the top of a hierarchy
         */
        public FatCat GetParent() {
            return Owner != null ? Owner : null;
        }

        public override bool Equals(object obj)
        {
            var slave = obj as WageSlave;
            return slave != null &&
                   Name == slave.Name &&
                   Salary == slave.Salary &&
                   EqualityComparer<FatCat>.Default.Equals(Owner, slave.Owner);
        }

        /*public override int GetHashCode()
        {
            return HashCode.Combine(Name, Salary, Owner);
        }*/
    }
	
    public class FatCat : ICapitalist
    {
        protected string Name { get; set; }
        protected int Salary { get; set; }
        protected FatCat Owner { get; set; }

        public FatCat(string name, int salary) {
            Name = name;
            Salary = salary;
            Owner = null;
        }

        public FatCat(string name, int salary, FatCat owner) {
            Name = name;
            Salary = salary;
            Owner = owner;
        }

        /**
         * @return the name of the capitalist
         */
        public String GetName() {
            return Name; 
        }

        /**
         * @return the salary of the capitalist, in dollars
         */
        public int GetSalary() {
            return Salary;
        }

        /**
         * @return true if this element has a parent, or false otherwise
         */
        public bool HasParent() {
            return Owner != null ? true : false;
        }

        /**
         * @return the parent of this element, or null if this represents the top of a hierarchy
         */
        public FatCat GetParent() {
            return Owner != null ? Owner : null;
        }

        public override bool Equals(object obj)
        {
            var cat = obj as FatCat;
            return cat != null &&
                   Name == cat.Name &&
                   Salary == cat.Salary &&
                   EqualityComparer<FatCat>.Default.Equals(Owner, cat.Owner);
        }

        /*public override int GetHashCode()
        {
            return HashCode.Combine(Name, Salary, Owner);
        }*/
    }
    public class MegaCorp : IHierarchy<ICapitalist, FatCat>
    {
        List<ICapitalist> MasterList = new List<ICapitalist>();
        
        Stack Log { get; set; }
        /**
         * Adds a given element to the hierarchy.
         * <p>
         * If the given element is already present in the hierarchy,
         * do not add it and return false
         * <p>
         * If the given element has a parent and the parent is not part of the hierarchy,
         * add the parent and then add the given element
         * <p>
         * If the given element has no parent but is a Parent itself,
         * add it to the hierarchy
         * <p>
         * If the given element has no parent and is not a Parent itself,
         * do not add it and return false
         *
         * @param capitalist the element to add to the hierarchy
         * @return true if the element was added successfully, false otherwise
         */
        public bool Add(ICapitalist element)
        {
            if(Has(element)){
                return false;
            }
            
            MasterList.Add(element);
            return true;
        }

        /**
         * @param capitalist the element to search for
         * @return true if the element has been added to the hierarchy, false otherwise
         */
        public bool Has(ICapitalist element)
        {
            return MasterList.Contains(element);
        }

        /**
         * @return all elements in the hierarchy,
         * or an empty set if no elements have been added to the hierarchy
         */
        public ISet<ICapitalist> GetElements()
        {
            HashSet<ICapitalist> Capitalists = new HashSet<ICapitalist>();
            foreach(ICapitalist i in MasterList){
                Capitalists.Add(i);
            }
            return Capitalists;
        }

        /**
         * @return all parent elements in the hierarchy,
         * or an empty set if no parents have been added to the hierarchy
         */
        public ISet<FatCat> GetParents()
        {
            HashSet<FatCat> Capitalists = new HashSet<FatCat>();
            IEnumerable<FatCat> query = from item in GetElements() where item.HasParent() select item.GetParent();
            foreach(FatCat i in query){
                Capitalists.Add(i);
                //Console.Write
            }
            return Capitalists;
        }

        /**
         * @param fatCat the parent whose children need to be returned
         * @return all elements in the hierarchy that have the given parent as a direct parent,
         * or an empty set if the parent is not present in the hierarchy or if there are no children
         * for the given parent
         */
        public ISet<ICapitalist> GetChildren(FatCat parent)
        {
            HashSet<ICapitalist> Capitalists = new HashSet<ICapitalist>();
            return Capitalists;
        }

        /**
         * @return a map in which the keys represent the parent elements in the hierarchy,
         * and the each value is a set of the direct children of the associate parent, or an
         * empty map if the hierarchy is empty.
         */
        public IDictionary<FatCat, ISet<ICapitalist>> GetHierarchy()
        {
            Dictionary<FatCat, ISet<ICapitalist>> Hierarchy = new Dictionary<FatCat, 	ISet<ICapitalist>>();
            return Hierarchy;
        }

        /**
         * @param capitalist
         * @return the parent chain of the given element, starting with its direct parent,
         * then its parent's parent, etc, or an empty list if the given element has no parent
         * or if its parent is not in the hierarchy
         */
        public IList<FatCat> GetParentChain(ICapitalist element)
        {
            List<FatCat> ParentChain = new List<FatCat>();
            //Console.WriteLine($"Child named:\t{element.GetName()}");
            /*if(element.HasParent()){
                ICapitalist parent = element.GetParent();
                Console.WriteLine($"Parent named:\t{parent.GetName()}");
                element = parent.GetParent();
                Console.WriteLine($"Parent named:\t{element.GetName()}");
                parent = element.GetParent();
                Console.WriteLine($"Parent named:\t{element.GetName()}");
            }*/
            while(element.HasParent()){
                Add(element);
                Console.WriteLine($"Name:\t{element.GetName()}");
                element = element.GetParent();
            }
            Add(element);
            Console.WriteLine($"Name:\t{element.GetName()}");
            return ParentChain;
        }
    }
    
class Program
{
    static void Main()
    {   
        MegaCorp megacorp = new MegaCorp();
        FatCat luke = new FatCat("Lucas", 60000);
        FatCat baker = new FatCat("Baker", 50000, luke);
        FatCat fry = new FatCat("Fryer", 50000, luke);
        FatCat wolf = new FatCat("Wolf", 5000, luke);
        WageSlave calvo = new WageSlave("Calvo", 60000, wolf);
        WageSlave graves = new WageSlave("Grave", 60000, baker);
        megacorp.Add(luke);
        megacorp.Add(baker);
        megacorp.Add(fry);
        megacorp.Add(wolf);
        megacorp.Add(calvo);
        megacorp.Add(graves);
        //ISet<ICapitalist> contents = megacorp.GetElements();
        //IEnumerable<string> query = from item in megacorp.GetElements() where item.HasParent() select item.GetName();
        IEnumerable<string> query = from item in megacorp.GetParentChain(calvo) select item.GetName();                      
                                
        foreach(string i in query){
            
            Console.WriteLine("Element Type: \tName: "+ i);
        }
        
    }
}

helloworld.cs

using System;

namespace HelloWorldApplication {
   
   class HelloWorld {
      
      static void Main(string[] args) {
         /* my first program in C# */
         Console.WriteLine("Hello World");
         Console.ReadKey();
      }
   }
}

Compile and Execute C# Sharp Online

using System;
class Object1 
{ 
    public static void Main(String[] args) { 
        Person1 p1, p2;        
        p1 = new Person1("大雄", 50);        
        p2 = new Person1("胖虎", 80);        
        p1.checkWeight();        
        p2.checkWeight();        
        p2.weight = 68;        
        p1.checkWeight();        
        p2.checkWeight();    
        
    }
}
    
    
class Person1 
{    
    public string name;    
    public int weight;        
    public Person1(string pName, int pWeight) 
    {       
        name   = pName;        
        weight = pWeight;    
     }
    public void checkWeight()    
    {        
        Console.Write(name+"體重 "+weight+" 公斤,");        
        if (weight < 70)          
          Console.WriteLine("很苗條!");        
        else         
          Console.WriteLine("很穩重!");    
    } 
    
}

https://pt.stackoverflow.com/q/359775/101

using static System.Console;
					
public class Program {
	public static void Main() {
		WriteLine(checkPalindrome("ana"));
		WriteLine(checkPalindrome("abba"));
		WriteLine(checkPalindrome("oki"));
	}
	static bool checkPalindrome(string inputString) {
        if(inputString.Length >= 1 && inputString.Length <= 100000) {
            for (var i = 0; i < inputString.Length / 2; i++) if (char.ToLower(inputString[i]) != char.ToLower(inputString[inputString.Length - i - 1])) return false;
			return true;
		}
		return false;
	}
}

//https://pt.stackoverflow.com/q/359775/101

Compile and Execute C# Sharp Online

using System;
using System.Collections.Generic;

public class Program
{
	  public class Product
    {
        public string Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public double Price
        {
            get;
            set;
        }

        public string Photo
        {
            get;
            set;
        }

    }
	
	 public class Item
    {
        public Product Product
        {
            get;
            set;
        }

        public int Quantity
        {
            get;
            set;
        }

    }
	
	public class ProductModel{
		
		private List<Product> products; // = new List<Product>();
		
		
		public ProductModel(){
		
			this.products = new List<Product>() { new Product{ Id = "p01", Name = "Name 1", Price = 5, Photo = "thumb1.gif"},
									  			           new Product{ Id = "p02", Name = "Name 2", Price = 5, Photo = "thumb2.gif"},
			                                      new Product{ Id = "p03", Name = "Name 3", Price = 10, Photo = "thumb3.gif"} };
			                                      
         			                                      
		}
		
		public List<Product> findAll(){
		   return this.products;
		}
	
	
	
	}
	
	public static void Main()
	{
		Console.WriteLine("Hello World !");
	}
}

prog

using System;

namespace InsertionSortDemo {
   class Example {
      static void Main(string[] args) {
         int[] arr = new int[10] { 23, 9, 85, 12, 99, 34, 60, 15, 100, 1 };
         int n = 10, i, j, val, flag; 
         Console.WriteLine("Insertion Sort");
         Console.Write("Initial array is: ");   
         for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " ");
         }   
         for (i = 1; i < n; i++) {
            val = arr[i];
            flag = 0;    
            for (j = i - 1; j >= 0 && flag != 1; ){
               if (val < arr[j]) {
                  arr[j + 1] = arr[j];
                  j--;
                  arr[j + 1] = val;
               }
               else flag = 1;
            }
         }    
         Console.Write("\nSorted Array is: ");   
         for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " "); 
         }          
      }        
   }   
}

rita

using System;
using System.IO;

namespace FileIOApplication {
   
   class Program {
      
      static void Main(string[] args) {
         FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, 
            FileAccess.ReadWrite);
         
         for (int i = 1; i <= 20; i++) {
            F.WriteByte((byte)i);
        
         }
         
         F.Position = 0;
         for (int i = 0; i <= 20; i++) {
            Console.Write(F.ReadByte() + " ");
         }
         F.Close();
         Console.ReadKey();
      }
   }
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.