Monday, August 15, 2011

Differentiate between Conversion Operator “IEnumerable” and “ToDictionary” of linq.

IEnumerable and To Dictionary both are Conversion Operator which are used to solved to conversion type Problems.

“AsEnumerable ” operator simply returns the source sequence as an object of type IEnumerable<T>. This kind of “conversion on the fly” makes it possible to call the general-purpose extension methods over source, even if its type has specific implementations of them

Signature-

public static IEnumerable<T> AsEnumerable<T>
(
this IEnumerable<T> source
);

“ToDictionary ” Conversion Operator is the instance of Dictionary (k,T) . The “keySelector ”predicate identifies the key of each item while “elementSelector ”, if provided, is used to extract each single item.

Key and elementSelector Predicate can be Used in following ways-

Example-

Public void ToDictionatyExample()
{
Var scoreRecords=
{
new {Name = "Alice",Score = 50 },
new {Name = "Bob",Score = 40 },
new {Name = "Cathy", Score = 45} };
Var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
Console.WriteLine("Bob's score: {0}", scoreRecordsDict("Bob"));
}

Result: Bob's score: { Name = Bob, Score = 40 }

No comments:

Post a Comment