Posted by: R Manimaran | July 20, 2011

SharePoint : Selecting KeyPair values using Lambda ToDictionary and ToLookup method

ToDictionary: It an LINQ extension method which stores the data as Key Value pairs. Here in the below I am fetching the Email Id and Title from a SharePoint List as a Key Value pairs.

Get the List using Lambda expression. If the specified list is not found, then it will return null.

SPList myList = oSPWeb.Lists.Cast<SPList>()
    .FirstOrDefault(l => l.Title == "ExternalPeople");

Get the Email and Tilte as key value pair. Before fetching do an filter operation where the Qualification is “BE”

IDictionary<string,string> NameswithEmail = myList.Items.Cast<SPListItem>()                                                                                .Where(itm => Convert.ToString(itm["Qualification"]) == "BE")                                                                                .ToDictionary(itm => Convert.ToString(itm["Email"]),
  itm => Convert.ToString(itm["Title"]));

Print the Key-value pairs using foreach

foreach (KeyValuePair<string, string> names in NameswithEmail)
{
    Console.WriteLine("Email:"+names.Key);
    Console.WriteLine("First Name:"+names.Value);
}

ToLookup: Allow you to specify Key and Values as TODictionary. The difference between ToLookup to ToDictionary is the former allows duplicates Keys while the latter does not.

Another difference is Lookups are immutable. i..e once you create a lookup you cannot add or remove elements from it.

In the above Dictionary collection NameswithEmail we have methods called Add and Remove. But we will not have any such methods in ILookup collection.

var myLookupItems = myList.Items.Cast<SPListItem>().ToLookup(itm => Convert.ToString(itm["Qualification"]), itm => itm);
var EmployeesBE = myLookupItems["MCA"];
 foreach (var str in EmployeesBE)
 {
   Console.WriteLine(str.Title);
 }

Instead of Var we can use the ILookup Enumerable as below

ILookup<string,SPListItem> myLookupItems1 = myList.Items.Cast<SPListItem>()

.ToLookup(itm => Convert.ToString(itm["Qualification"]),

itm => itm);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: