Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Grouping using Lambda Expressions

Posted by Paul on November 4, 2011


// Group the list based on Serial Number

// Result should be SerialNumber, Month, SUM(Value)

/// Good Challenge?

private void DoGrouping()
{
    IList<Item> list = new List<Item>();
    list.Add(new Item() { SerialNumber = 1, Month = “Jan-2010”, Value = 2 });
    list.Add(new Item() { SerialNumber = 1, Month = “Jan-2010”, Value = 5 });
    list.Add(new Item() { SerialNumber = 2, Month = “Feb-2010”, Value = 1 });
    list.Add(new Item() { SerialNumber = 2, Month = “Feb-2010”, Value = 6 });
    list.Add(new Item() { SerialNumber = 2, Month = “Feb-2010”, Value = 2 });
    list.Add(new Item() { SerialNumber = 3, Month = “Mar-2010”, Value = 7 });
    list.Add(new Item() { SerialNumber = 3, Month = “Mar-2010”, Value = 4 });

    IList<Item> groupedList = list.GroupBy(i => i.SerialNumber).Select(g => new Item() { SerialNumber = g.Key, Month = g.First().Month, Value = g.Sum(gr => gr.Value) }).ToList<Item>();
}

public class Item
{
    public int SerialNumber;
    public string Month;
    public int Value;
}

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s