.NET Zone is brought to you in partnership with:

Senthil Kumar is a Software Engineer who has around 3 years of experience in IT industry. He is currently working as a Software Engineer in Bangalore and works mainly on the Windows or Client Development technologies and has good working experience in C#/.NET, Delphi, Winforms and SQL Server. He is also a Microsoft Technology Certified Professional in ASP.NET. He Blogs at http://www.ginktage.com and http://www.windowsphonerocks.com. He enjoys learning as much as he can about all things related to technologies to get a well-rounded exposure of technologies that surround him. Senthil completed his Master of Computer Applications from Christ College (Autonomous), Bangalore in the year 2009 and is a MCA Rank Holder. He has passion for Microsoft technologies especially Windows Phone development. You can connect with him on Twitter at (http://twitter.com/isenthil) , on Facebook at (http://www.facebook.com/kumarbsenthil) and his blog (www.ginktage.com). Senthil is a DZone MVB and is not an employee of DZone and has posted 131 posts at DZone. You can read more from them at their website. View Full User Profile

How to Return Dictionary As a Result From a LINQ Query in C#?

02.13.2013
| 11641 views |
  • submit to reddit

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# ?

Published at DZone with permission of Senthil Kumar, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)