How to return Dictionary as result from a LINQ Query in C# ?

This article will provide a code snippet and explains how to return Dictionary as result from a LINQ Query in C#.

There are times when you want to retrieve only the ID(distinct) and the name from the database table using LINQ . In scenarios like this , one can use the ToDictionary method to place the necessary properties to the dictionary and return them.

Below is a sample sourecode demonstrating the usage of ToDictionary method in LINQ Query

public class BlockbusterMovie

{

public string Name { get; set; }

public int ID { get; set; }

}

public class BlockbusterMovies : List<BlockbusterMovie>

{

public BlockbusterMovies()

{

Add(new BlockbusterMovie { Name = "Vishwaroopam", ID = 1 });

Add(new BlockbusterMovie { Name = "Endhiran", ID = 2 });

Add(new BlockbusterMovie { Name = "Thuppaki", ID = 3 });

Add(new BlockbusterMovie { Name = "Mankatha", ID = 4 });

}

}

The BlockbusterMovies class has the collection of movies which is used in the below code snippet to return the dictionary based on the ID and Name.

private void Form1_Load(object sender, EventArgs e)

{

List<BlockbusterMovie> movies = new BlockbusterMovies();

var LstMovies = movies.ToDictionary(Field => Field.ID, mc => mc.Name);

}
How to return Dictionary as result from a LINQ Query in C# ?

How to return Dictionary as result from a LINQ Query in C# ?

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No Responses

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...