Thursday, 28 July 2011

Grouping list of objects

There are two methods for grouping list of  objects in c sharp. one is using  Dictionary and other one is using linq to objects

Using StoredDictionary
// 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);
}

Using Linq to objects:

Linq to objects works from 3.0 .net frame work

var query = from c in contacts 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