Group by with multiple columns using lambda












96















How can I group by with multiple columns using lambda?



I saw examples of how to do it using linq to entities, but I am looking for lambda form.










share|improve this question

























  • Do you have a specific query in mind?

    – Brian Dishaw
    Aug 4 '11 at 2:10
















96















How can I group by with multiple columns using lambda?



I saw examples of how to do it using linq to entities, but I am looking for lambda form.










share|improve this question

























  • Do you have a specific query in mind?

    – Brian Dishaw
    Aug 4 '11 at 2:10














96












96








96


8






How can I group by with multiple columns using lambda?



I saw examples of how to do it using linq to entities, but I am looking for lambda form.










share|improve this question
















How can I group by with multiple columns using lambda?



I saw examples of how to do it using linq to entities, but I am looking for lambda form.







c# .net entity-framework lambda






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 12 '16 at 10:53









Jesuraja

2,84921338




2,84921338










asked Aug 4 '11 at 1:46









NaorNaor

10k34118225




10k34118225













  • Do you have a specific query in mind?

    – Brian Dishaw
    Aug 4 '11 at 2:10



















  • Do you have a specific query in mind?

    – Brian Dishaw
    Aug 4 '11 at 2:10

















Do you have a specific query in mind?

– Brian Dishaw
Aug 4 '11 at 2:10





Do you have a specific query in mind?

– Brian Dishaw
Aug 4 '11 at 2:10












4 Answers
4






active

oldest

votes


















195














var query = source.GroupBy(x => new { x.Column1, x.Column2 });





share|improve this answer


























  • Would this actually work? I would think that the equality test for each object you're grouping by would fail since they're objects and not structs.

    – Jacob
    Aug 4 '11 at 2:17











  • @Aducci: Thanks. Can you example how can I get IEnumerable of the group items?

    – Naor
    Aug 4 '11 at 2:22






  • 4





    @Jacob - Anonymous types are immutable classes with properly overriden GetHashCode & Equals methods. They where designed for exactly this kind of use case.

    – Enigmativity
    Aug 4 '11 at 2:57






  • 5





    @Naor - GroupBy returns an IEnumerable<IGrouping<TKey, TSource>> which is essentially an IEnumerable<IEnumerable<TSource>> with a Key property on the inner enumerable. Does that help you to get the "IEnumerable" of the group items?

    – Enigmativity
    Aug 4 '11 at 3:00











  • @Enigmativity: Thanks!

    – Naor
    Aug 4 '11 at 8:03



















6














if your table is like this



rowId     col1    col2    col3    col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5


var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});





share|improve this answer



















  • 2





    It is very important to note that AsEnumerable will bring the entire table into memory before grouping it. That definitely matters on some tables. See this answer for more insight: stackoverflow.com/questions/17968469/…

    – Brandon Barkley
    Apr 19 '18 at 16:32





















3














Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.



return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();


Where CustomerGroupingKey takes the group keys:



    private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}

public string Country { get; }

public string Gender { get; }
}





share|improve this answer





















  • 1





    Probably will save someone some time: it's better to use default constructions with object initializaters. The approach in the sample code above will not be treated by ORMs like EF Core well.

    – Konstantin
    Apr 6 '17 at 19:13





















-1














     class Element
{
public string Company;
public string TypeOfInvestment;
public decimal Worth;
}

class Program
{
static void Main(string args)
{
List<Element> elements = new List<Element>()
{
new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
};

//Group by on multiple column in LINQ (Query Method)
var query = from e in elements
group e by new{e.TypeOfInvestment,e.Company} into eg
select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};



foreach (var item in query)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
}


//Group by on multiple column in LINQ (Lambda Method)
var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
.Select(g =>
new
{
company = g.Key.Company,
TypeOfInvestment = g.Key.TypeOfInvestment,
Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
}
);
foreach (var item in CompanyDetails)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
}
Console.ReadLine();

}
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6935264%2fgroup-by-with-multiple-columns-using-lambda%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    195














    var query = source.GroupBy(x => new { x.Column1, x.Column2 });





    share|improve this answer


























    • Would this actually work? I would think that the equality test for each object you're grouping by would fail since they're objects and not structs.

      – Jacob
      Aug 4 '11 at 2:17











    • @Aducci: Thanks. Can you example how can I get IEnumerable of the group items?

      – Naor
      Aug 4 '11 at 2:22






    • 4





      @Jacob - Anonymous types are immutable classes with properly overriden GetHashCode & Equals methods. They where designed for exactly this kind of use case.

      – Enigmativity
      Aug 4 '11 at 2:57






    • 5





      @Naor - GroupBy returns an IEnumerable<IGrouping<TKey, TSource>> which is essentially an IEnumerable<IEnumerable<TSource>> with a Key property on the inner enumerable. Does that help you to get the "IEnumerable" of the group items?

      – Enigmativity
      Aug 4 '11 at 3:00











    • @Enigmativity: Thanks!

      – Naor
      Aug 4 '11 at 8:03
















    195














    var query = source.GroupBy(x => new { x.Column1, x.Column2 });





    share|improve this answer


























    • Would this actually work? I would think that the equality test for each object you're grouping by would fail since they're objects and not structs.

      – Jacob
      Aug 4 '11 at 2:17











    • @Aducci: Thanks. Can you example how can I get IEnumerable of the group items?

      – Naor
      Aug 4 '11 at 2:22






    • 4





      @Jacob - Anonymous types are immutable classes with properly overriden GetHashCode & Equals methods. They where designed for exactly this kind of use case.

      – Enigmativity
      Aug 4 '11 at 2:57






    • 5





      @Naor - GroupBy returns an IEnumerable<IGrouping<TKey, TSource>> which is essentially an IEnumerable<IEnumerable<TSource>> with a Key property on the inner enumerable. Does that help you to get the "IEnumerable" of the group items?

      – Enigmativity
      Aug 4 '11 at 3:00











    • @Enigmativity: Thanks!

      – Naor
      Aug 4 '11 at 8:03














    195












    195








    195







    var query = source.GroupBy(x => new { x.Column1, x.Column2 });





    share|improve this answer















    var query = source.GroupBy(x => new { x.Column1, x.Column2 });






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 25 '14 at 14:41

























    answered Aug 4 '11 at 2:11









    AducciAducci

    20.6k75561




    20.6k75561













    • Would this actually work? I would think that the equality test for each object you're grouping by would fail since they're objects and not structs.

      – Jacob
      Aug 4 '11 at 2:17











    • @Aducci: Thanks. Can you example how can I get IEnumerable of the group items?

      – Naor
      Aug 4 '11 at 2:22






    • 4





      @Jacob - Anonymous types are immutable classes with properly overriden GetHashCode & Equals methods. They where designed for exactly this kind of use case.

      – Enigmativity
      Aug 4 '11 at 2:57






    • 5





      @Naor - GroupBy returns an IEnumerable<IGrouping<TKey, TSource>> which is essentially an IEnumerable<IEnumerable<TSource>> with a Key property on the inner enumerable. Does that help you to get the "IEnumerable" of the group items?

      – Enigmativity
      Aug 4 '11 at 3:00











    • @Enigmativity: Thanks!

      – Naor
      Aug 4 '11 at 8:03



















    • Would this actually work? I would think that the equality test for each object you're grouping by would fail since they're objects and not structs.

      – Jacob
      Aug 4 '11 at 2:17











    • @Aducci: Thanks. Can you example how can I get IEnumerable of the group items?

      – Naor
      Aug 4 '11 at 2:22






    • 4





      @Jacob - Anonymous types are immutable classes with properly overriden GetHashCode & Equals methods. They where designed for exactly this kind of use case.

      – Enigmativity
      Aug 4 '11 at 2:57






    • 5





      @Naor - GroupBy returns an IEnumerable<IGrouping<TKey, TSource>> which is essentially an IEnumerable<IEnumerable<TSource>> with a Key property on the inner enumerable. Does that help you to get the "IEnumerable" of the group items?

      – Enigmativity
      Aug 4 '11 at 3:00











    • @Enigmativity: Thanks!

      – Naor
      Aug 4 '11 at 8:03

















    Would this actually work? I would think that the equality test for each object you're grouping by would fail since they're objects and not structs.

    – Jacob
    Aug 4 '11 at 2:17





    Would this actually work? I would think that the equality test for each object you're grouping by would fail since they're objects and not structs.

    – Jacob
    Aug 4 '11 at 2:17













    @Aducci: Thanks. Can you example how can I get IEnumerable of the group items?

    – Naor
    Aug 4 '11 at 2:22





    @Aducci: Thanks. Can you example how can I get IEnumerable of the group items?

    – Naor
    Aug 4 '11 at 2:22




    4




    4





    @Jacob - Anonymous types are immutable classes with properly overriden GetHashCode & Equals methods. They where designed for exactly this kind of use case.

    – Enigmativity
    Aug 4 '11 at 2:57





    @Jacob - Anonymous types are immutable classes with properly overriden GetHashCode & Equals methods. They where designed for exactly this kind of use case.

    – Enigmativity
    Aug 4 '11 at 2:57




    5




    5





    @Naor - GroupBy returns an IEnumerable<IGrouping<TKey, TSource>> which is essentially an IEnumerable<IEnumerable<TSource>> with a Key property on the inner enumerable. Does that help you to get the "IEnumerable" of the group items?

    – Enigmativity
    Aug 4 '11 at 3:00





    @Naor - GroupBy returns an IEnumerable<IGrouping<TKey, TSource>> which is essentially an IEnumerable<IEnumerable<TSource>> with a Key property on the inner enumerable. Does that help you to get the "IEnumerable" of the group items?

    – Enigmativity
    Aug 4 '11 at 3:00













    @Enigmativity: Thanks!

    – Naor
    Aug 4 '11 at 8:03





    @Enigmativity: Thanks!

    – Naor
    Aug 4 '11 at 8:03













    6














    if your table is like this



    rowId     col1    col2    col3    col4
    1 a e 12 2
    2 b f 42 5
    3 a e 32 2
    4 b f 44 5


    var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});





    share|improve this answer



















    • 2





      It is very important to note that AsEnumerable will bring the entire table into memory before grouping it. That definitely matters on some tables. See this answer for more insight: stackoverflow.com/questions/17968469/…

      – Brandon Barkley
      Apr 19 '18 at 16:32


















    6














    if your table is like this



    rowId     col1    col2    col3    col4
    1 a e 12 2
    2 b f 42 5
    3 a e 32 2
    4 b f 44 5


    var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});





    share|improve this answer



















    • 2





      It is very important to note that AsEnumerable will bring the entire table into memory before grouping it. That definitely matters on some tables. See this answer for more insight: stackoverflow.com/questions/17968469/…

      – Brandon Barkley
      Apr 19 '18 at 16:32
















    6












    6








    6







    if your table is like this



    rowId     col1    col2    col3    col4
    1 a e 12 2
    2 b f 42 5
    3 a e 32 2
    4 b f 44 5


    var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});





    share|improve this answer













    if your table is like this



    rowId     col1    col2    col3    col4
    1 a e 12 2
    2 b f 42 5
    3 a e 32 2
    4 b f 44 5


    var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Apr 19 '13 at 13:51









    KhanSharpKhanSharp

    7,80343747




    7,80343747








    • 2





      It is very important to note that AsEnumerable will bring the entire table into memory before grouping it. That definitely matters on some tables. See this answer for more insight: stackoverflow.com/questions/17968469/…

      – Brandon Barkley
      Apr 19 '18 at 16:32
















    • 2





      It is very important to note that AsEnumerable will bring the entire table into memory before grouping it. That definitely matters on some tables. See this answer for more insight: stackoverflow.com/questions/17968469/…

      – Brandon Barkley
      Apr 19 '18 at 16:32










    2




    2





    It is very important to note that AsEnumerable will bring the entire table into memory before grouping it. That definitely matters on some tables. See this answer for more insight: stackoverflow.com/questions/17968469/…

    – Brandon Barkley
    Apr 19 '18 at 16:32







    It is very important to note that AsEnumerable will bring the entire table into memory before grouping it. That definitely matters on some tables. See this answer for more insight: stackoverflow.com/questions/17968469/…

    – Brandon Barkley
    Apr 19 '18 at 16:32













    3














    Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.



    return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
    .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
    .SelectMany(a => a)
    .ToList();


    Where CustomerGroupingKey takes the group keys:



        private class CustomerGroupingKey
    {
    public CustomerGroupingKey(string country, string gender)
    {
    Country = country;
    Gender = gender;
    }

    public string Country { get; }

    public string Gender { get; }
    }





    share|improve this answer





















    • 1





      Probably will save someone some time: it's better to use default constructions with object initializaters. The approach in the sample code above will not be treated by ORMs like EF Core well.

      – Konstantin
      Apr 6 '17 at 19:13


















    3














    Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.



    return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
    .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
    .SelectMany(a => a)
    .ToList();


    Where CustomerGroupingKey takes the group keys:



        private class CustomerGroupingKey
    {
    public CustomerGroupingKey(string country, string gender)
    {
    Country = country;
    Gender = gender;
    }

    public string Country { get; }

    public string Gender { get; }
    }





    share|improve this answer





















    • 1





      Probably will save someone some time: it's better to use default constructions with object initializaters. The approach in the sample code above will not be treated by ORMs like EF Core well.

      – Konstantin
      Apr 6 '17 at 19:13
















    3












    3








    3







    Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.



    return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
    .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
    .SelectMany(a => a)
    .ToList();


    Where CustomerGroupingKey takes the group keys:



        private class CustomerGroupingKey
    {
    public CustomerGroupingKey(string country, string gender)
    {
    Country = country;
    Gender = gender;
    }

    public string Country { get; }

    public string Gender { get; }
    }





    share|improve this answer















    Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.



    return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
    .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
    .SelectMany(a => a)
    .ToList();


    Where CustomerGroupingKey takes the group keys:



        private class CustomerGroupingKey
    {
    public CustomerGroupingKey(string country, string gender)
    {
    Country = country;
    Gender = gender;
    }

    public string Country { get; }

    public string Gender { get; }
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 23 '17 at 11:47









    Community

    11




    11










    answered Nov 16 '16 at 6:16









    David McEleneyDavid McEleney

    1,2241318




    1,2241318








    • 1





      Probably will save someone some time: it's better to use default constructions with object initializaters. The approach in the sample code above will not be treated by ORMs like EF Core well.

      – Konstantin
      Apr 6 '17 at 19:13
















    • 1





      Probably will save someone some time: it's better to use default constructions with object initializaters. The approach in the sample code above will not be treated by ORMs like EF Core well.

      – Konstantin
      Apr 6 '17 at 19:13










    1




    1





    Probably will save someone some time: it's better to use default constructions with object initializaters. The approach in the sample code above will not be treated by ORMs like EF Core well.

    – Konstantin
    Apr 6 '17 at 19:13







    Probably will save someone some time: it's better to use default constructions with object initializaters. The approach in the sample code above will not be treated by ORMs like EF Core well.

    – Konstantin
    Apr 6 '17 at 19:13













    -1














         class Element
    {
    public string Company;
    public string TypeOfInvestment;
    public decimal Worth;
    }

    class Program
    {
    static void Main(string args)
    {
    List<Element> elements = new List<Element>()
    {
    new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
    new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
    new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
    new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
    new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
    new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
    new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
    new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
    new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
    new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
    };

    //Group by on multiple column in LINQ (Query Method)
    var query = from e in elements
    group e by new{e.TypeOfInvestment,e.Company} into eg
    select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};



    foreach (var item in query)
    {
    Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
    }


    //Group by on multiple column in LINQ (Lambda Method)
    var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
    .Select(g =>
    new
    {
    company = g.Key.Company,
    TypeOfInvestment = g.Key.TypeOfInvestment,
    Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
    }
    );
    foreach (var item in CompanyDetails)
    {
    Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
    }
    Console.ReadLine();

    }
    }





    share|improve this answer




























      -1














           class Element
      {
      public string Company;
      public string TypeOfInvestment;
      public decimal Worth;
      }

      class Program
      {
      static void Main(string args)
      {
      List<Element> elements = new List<Element>()
      {
      new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
      new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
      new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
      new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
      new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
      new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
      new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
      new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
      new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
      new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
      };

      //Group by on multiple column in LINQ (Query Method)
      var query = from e in elements
      group e by new{e.TypeOfInvestment,e.Company} into eg
      select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};



      foreach (var item in query)
      {
      Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
      }


      //Group by on multiple column in LINQ (Lambda Method)
      var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
      .Select(g =>
      new
      {
      company = g.Key.Company,
      TypeOfInvestment = g.Key.TypeOfInvestment,
      Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
      }
      );
      foreach (var item in CompanyDetails)
      {
      Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
      }
      Console.ReadLine();

      }
      }





      share|improve this answer


























        -1












        -1








        -1







             class Element
        {
        public string Company;
        public string TypeOfInvestment;
        public decimal Worth;
        }

        class Program
        {
        static void Main(string args)
        {
        List<Element> elements = new List<Element>()
        {
        new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
        new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
        new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
        new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
        new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
        new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
        new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
        new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
        new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
        new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
        };

        //Group by on multiple column in LINQ (Query Method)
        var query = from e in elements
        group e by new{e.TypeOfInvestment,e.Company} into eg
        select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};



        foreach (var item in query)
        {
        Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
        }


        //Group by on multiple column in LINQ (Lambda Method)
        var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
        .Select(g =>
        new
        {
        company = g.Key.Company,
        TypeOfInvestment = g.Key.TypeOfInvestment,
        Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
        }
        );
        foreach (var item in CompanyDetails)
        {
        Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
        }
        Console.ReadLine();

        }
        }





        share|improve this answer













             class Element
        {
        public string Company;
        public string TypeOfInvestment;
        public decimal Worth;
        }

        class Program
        {
        static void Main(string args)
        {
        List<Element> elements = new List<Element>()
        {
        new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
        new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
        new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
        new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
        new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
        new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
        new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
        new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
        new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
        new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
        };

        //Group by on multiple column in LINQ (Query Method)
        var query = from e in elements
        group e by new{e.TypeOfInvestment,e.Company} into eg
        select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};



        foreach (var item in query)
        {
        Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
        }


        //Group by on multiple column in LINQ (Lambda Method)
        var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
        .Select(g =>
        new
        {
        company = g.Key.Company,
        TypeOfInvestment = g.Key.TypeOfInvestment,
        Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
        }
        );
        foreach (var item in CompanyDetails)
        {
        Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
        }
        Console.ReadLine();

        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 2 '17 at 9:48









        Sandeep TripathiSandeep Tripathi

        92




        92






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6935264%2fgroup-by-with-multiple-columns-using-lambda%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python