Quantcast
Channel: *****## R.MARAN. ## *****
Viewing all articles
Browse latest Browse all 39

SharePoint : Selecting KeyPair values using Lambda ToDictionary and ToLookup method

$
0
0

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);



Viewing all articles
Browse latest Browse all 39

Trending Articles