Linq Sample

Language Integrated Query, or LINQ for short (pronounced “link”), is a
set of Microsoft .NET Framework language enhancements and libraries
built by Microsoft to make working with simpler and more intuitive. LINQ provides a layer of programming abstraction between .NET languages and an ever-growing number of
underlying data sources.

C# 2.0 Approach
 
 Features of C# 2.0,being inline Delegates and Generic types. Its approach is to first sort the
collection by the LastName property using a comparison delegate, and then
it groups the collection by State property in a SortedDictionary collection. 

C# 2.0 code for grouping and sorting contact records—

List<Contact> contacts = Contact.SampleData();
// sort by last name
contacts.Sort(
delegate(Contact c1, Contact c2)
{
if (c1 != null && c2 != null)
return string.Compare(
c1.LastName, c2.LastName);
return 0;
}
);
// sort and group by state (using a sorted dictionary)
SortedDictionary<string, List<Contact>> groups =
new SortedDictionary<string, List<Contact>>();
foreach (Contact c in contacts)
{
if (groups.ContainsKey(c.State))
{
groups[c.State].Add(c);
}
else
{
List<Contact> list = new List<Contact>();
list.Add(c);
groups.Add(c.State, list);
}
}
// write out the results
foreach (KeyValuePair<string, List<Contact>>
group in groups)
{
Console.WriteLine(”State: “ + group.Key);
foreach (Contact c in group.Value)
Console.WriteLine(” {0} {1}”,
c.FirstName, c.LastName);
}

 

LINQ Approach

LINQ to Objects, the LINQ features designed to add query functionality
over in-memory collections, makes this scenario very easy to implement.

C# 3.0 code for Linq

List<Contact> contacts = Contact.SampleData();
// perform the LINQ query
var query = from c in contacts
orderby c.State, c.LastName
group c by c.State;
// write out the results
foreach (var group in query)
{
Console.WriteLine(”State: “ + group.Key);
foreach (Contact c in group)
Console.WriteLine(” {0} {1}”,
c.FirstName, c.LastName);
}
 

 

No comments:

Post a Comment