Introduction:

 

In this article we will learn, how to ToDictionary() method in LINQ or what is ToDictionary() method in LINQ C# Asp.net MVC with example.

Description:

In LINQ, ToDictionary method is used to convert list or collection (IEnumerable<T>) items to new dictionary object (Dictionary<TKey,TValue>) and it will optimize list / collection items by getting only required values.

 

Example of LINQ ToDictionary() Method

Following is the example of using LINQ ToDictionary method to convert collection to new dictionary object.

 

 using System;
using System.Collections.Generic;
using System.Linq;
namespace SQLTutorialsPoint
{
    class Employee
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            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);               
            }
 
            Console.ReadLine();
        }
    }
}

 

 

As you see above example we are converting “Employee” collection to dictionary object and getting values from two fields (ID and Name)


Now we will run and see the output.


 Use LINQ ToDictionary Method


In this article we learned, how we can use LINQ ToDictionary() method to convert list / collection items to new dictionary object in c# example.

 

I hope it will help to you after reading.

comments


Leave a comment

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

You may also like