Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication4
- {
- class Program
- {
- static void Main(string[] args)
- {
- // this is how to add information to dictionary
- Customer customer1 = new Customer()
- {
- ID = 101,
- name = "Stefan",
- salary = 10000
- };
- Customer customer2 = new Customer()
- {
- ID = 102,
- name = "Harvey",
- salary = 9000
- };
- // this is how to put the information in the dictionary
- // pay attention we cannot add a value more than once
- Dictionary<int, Customer> dictionaryCustomers = new Dictionary<int, Customer>();
- dictionaryCustomers.Add(customer1.ID, customer1);
- dictionaryCustomers.Add(customer2.ID, customer2);
- //Customer customer119 = dictionaryCustomers[101];
- // check for key containing
- //if (!dictionaryCustomers.ContainsKey(customer1.ID))
- //{
- // dictionaryCustomers.Add(customer1.ID, customer1);
- //}
- // this is how we could use the information
- Console.WriteLine("ID-{0} name-{1} salary-{2}", customer1.ID, customer1.name, customer1.salary);
- // this is how to print a dictionary in a list
- foreach (KeyValuePair<int, Customer> someValue in dictionaryCustomers)
- {
- Console.WriteLine("Key: {0}", someValue.Key);
- Customer cust = someValue.Value;
- Console.WriteLine("ID: {0} Name: {1} Salary:{2}", cust.ID, cust.name, cust.salary);
- Console.WriteLine("--------------------------------------------------------------");
- }
- // print only the value which we need
- foreach (Customer cust in dictionaryCustomers.Values)
- {
- Console.WriteLine("ID: {0} Name: {1} Salary:{2}", cust.ID, cust.name, cust.salary);
- Console.WriteLine("--------------------------------------------------------------");
- }
- //how to get value
- Customer cast;
- dictionaryCustomers.TryGetValue(101, out cast);
- for (int i = 101; i < 103; i++)
- {
- if (dictionaryCustomers.TryGetValue(i, out cast))
- {
- cast.salary += 100;
- }
- }
- foreach (KeyValuePair<int, Customer> item in dictionaryCustomers)
- {
- Customer customerTest = item.Value;
- Console.WriteLine("ID: {0} Name: {1} Salary:{2}", customerTest.ID, customerTest.name, customerTest.salary);
- Console.WriteLine("###################################################################");
- }
- }
- // this is how to create a new dictionary
- public class Customer
- {
- public int ID { get; set; }
- public string name { get; set; }
- public int salary { get; set; }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment