Hi guys i want to convert employee collection List to a Dictionary in c#.

This is employee list:

List<Employee> Employee = new List<Employee>(){
            new Employee() {  Name = "Suresh", ID  = 1},
            new Employee() {  Name = "Sekher", ID =  2 },
              new Employee() {  Name = "Sumit", ID =  3 },
            new Employee() {  Name = "Pankaj", ID = 4 },
            new Employee() {  Name = "Rahul", ID = 5 }}.ToList();

  

Please help me.

1 Answers

  1. Aditya Kumar Patel
    Re:Convert List type object to Dictionary type arya mercy
    10/7/2018 6:43:59 PM

    Dictionary<TKey, TValue> is a generic collection included in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of TValue.


    Try to use it:

    List<Employee> Employee = new List<Employee>(){
                new Employee() {  Name = "Suresh",ID  = 1},
                new Employee() {  Name = "Sekher", ID=  2 },
                  new Employee() {  Name = "Sumit", ID=  3 },
                new Employee() {  Name = "Pankaj", ID = 4},
                new Employee() {  Name = "Rahul", ID = 5}}.ToList();
     
     
                var Emp = Employee.ToDictionary(x => x.ID, x =>x.Name);
     
                Console.WriteLine("--------Employees----------");
                foreach (var item in Emp)
                {               
                    Console.WriteLine(" ID:" + item.Key +"Name:"+item.Value);               
                }

    I hope it will help to you.


Leave a answer

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like