Linq Casting: ToDictionary()

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)

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

This example will use the following Blogger class.


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


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


// 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


 Hope it helps.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
Linq Casting: ToDictionary() Pieter Brinkman avatarAuthor: Pieter Brinkman ()

Pieter is Technical Marketing Manager for Sitecore Netherlands and owner of Gaatverweg.nl. He has more than ten years experience with software developing in multiple programming languages and with different Content Management Systems. Before joining Sitecore Pieter was a lead developer for multiple Sitecore and .Net projects, he joined Sitecore in 2011 as an Solution Architect in The Netherlands, after two years as an Solution Architect he joined the Technical Marketing department. In the role as Techinical Marketing Manager he is responsible for the Global MVP program and the Sitecore technical branding strategy. You can follow Pieter on twitter: @pieterbrink123 or Google+

Linq Casting: ToDictionary() WebsiteLinq Casting: ToDictionary() TwitterLinq Casting: ToDictionary() Google PlusLinq Casting: ToDictionary() Linkedin

Related posts

LINQ: Creating a if statement in Linq query
WCF webservice error with DBML objects

0 Responses to Linq Casting: ToDictionary()

Comments
Tweets
Pingbacks
  • Click on a tab to select how you'd like to leave your comment

    Leave a Reply

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

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>