Linq Casting: ToDictionary()

by Pieter Brinkman 23. June 2009 04:03

In this post I will give an example how to cast a GenericList to Dictionary.

This example will use the following Blogger class.

[code:c#]

public class Blogger
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public string Blog { get; set; }
}

[/code]

 

The example will cast a List<Blogger> to a dictionary with key FirstName, Lastname and value the Age of the blogger.

[code:c#]

// DECLARE PERSONLIST

List<Blogger> personList = new List<Blogger>();
personList.Add(new Blogger { FirstName = "Pieter", LastName = "Brinkman", Age = 27, Blog = "http://blog.newguid.net" });
personList.Add(new Blogger { FirstName = "Mark", LastName = "van Aalst", Age = 26, Blog = "http://www.markvanaalst.com/" });
personList.Add(new Blogger { FirstName = "Bas", LastName = "Hammendorp", Age = 32, Blog = "http://www.hammendorp.net/" });


// CREATE NEW DICTIONARY FROM LIST
// with key FirstName + LastName and value Age

Dictionary<string, int> AgeDictionary =
 personList.ToDictionary(x => x.FirstName + " " + x.LastName,
       x => x.Age,
       StringComparer.OrdinalIgnoreCase);


// GENERATE OUTPUT

foreach (KeyValuePair<string, int> item in AgeDictionary)
 Response.Write("key: " + item.Key + " - value: " + item.Value + "<br />");


//// OUTPUT
//key: Pieter Brinkman - value: 27
//key: Mark van Aalst - value: 26
//key: Bas Hammendorp - value: 32

[/code]

 Hope it helps.

Tags: , , ,

Linq

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Me

My name is Pieter Brinkman I am Solution Architect for Sitecore in The Netherlands. My interests are mainly ASP.NET, MSSQL and Content Management Systems.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

RecentComments

Comment RSS

Most comments