Iterate dictionary using Linq C#

Iterate dictionary using Linq C#

LINQ:

Language Integrated Query is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, originally released as a major part of .NET Framework 3.5 in 2007.

There are many ways to iterate a dictionary in C# like using for loop, foreach loop etc. Linq another approach which makes your code readability shorten in nature. Let’s see how we can iterate a dictionary using Linq in C#. In this example we have a dictionary which contains Day and Name of the day. We will pull all days name.

public static void PopulateDictWithLinq()
{
	Dictionary<int,string> mDict=new Dictionary<int,string>();
	mDict.Add(1,"Sunday");
	mDict.Add(2,"Monday");
	mDict.Add(3,"Tuesday");
	mDict.Add(4,"Wednesday");
	mDict.Add(5,"Thursday");
	mDict.Add(6,"Friday");
	mDict.Add(7,"Saturday");
	
	var daysName = mDict.ToDictionary(x => x.Value);
}

In above example daysName object holds all your day from your dictionary which you can use as a list or print on the screen.

Leave a Reply

Your email address will not be published. Required fields are marked *