Group by with multiple columns using lambda

后端 未结 5 822
一个人的身影
一个人的身影 2020-12-02 16:09

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.

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 16:58

    I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:

    var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
                                        .Select(r => new ResultGrouping {
                                            IdObj1= r.Key.IdObj1,
                                            IdObj2= r.Key.IdObj2,
                                            IdObj3= r.Key.IdObj3,
                                            Results = r.ToArray(),
                                            Count = r.Count()
                                        });
    
    
    
    private class ResultGrouping
            {
                public short IdObj1{ get; set; }
                public short IdObj2{ get; set; }
                public int IdObj3{ get; set; }
    
                public ResultCsvImport[] Results { get; set; }
                public int Count { get; set; }
            }
    

    Where resultRecords is my initial list I'm grouping, and its a List. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3

提交回复
热议问题