Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda


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



Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:
dotnet ,how-to ,microsoft ,tools ,collections ,visual studio ,.net & windows ,c-sharp

Published at DZone with permission of Senthil Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}