使用Lambda按多列分组


122

如何使用Lambda对多个列进行分组?

我看到了使用linq对实体执行此操作的示例,但我正在寻找lambda形式。

Answers:


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

这实际可行吗?我认为对您分组的每个对象进行的相等性测试将失败,因为它们是对象而不是结构。
雅各布

@Aducci:谢谢。您能举例说明如何获得组项目的IEnumerable吗?
瑙尔,

6
@Jacob-匿名类型是具有适当重写GetHashCodeEquals方法的不可变类。他们正是针对这种用例而设计的。
谜团

5
@Naor- GroupBy返回一个IEnumerable<IGrouping<TKey, TSource>>本质上为IEnumerable<IEnumerable<TSource>>且具有Key内部可枚举属性的an 。这是否有助于您获得组项目的“ IEnumerable”?
Enigmativity

如果我的'source'变量是Dictionary Collection,则无法使用。有什么建议吗?
Joao Paulo


4

除了上面的aduchis答案之外,如果您随后需要根据这些按键分组,则可以定义一个类来包装许多键。

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

其中CustomerGroupingKey使用组密钥:

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

        public string Country { get; }

        public string Gender { get; }
    }

1
可能会节省一些时间:最好将默认构造与对象初始化一起使用。上面的示例代码中的方法不会像EF Core这样的ORM很好地对待。
康斯坦丁

2
     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();

        }
    }

1

我想出了一个定义类的组合,例如David的答案,但不要求将Where类与之配合使用。看起来像:

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; }
        }

resultRecords我要分组的初始列表在哪里,以及它的List<ResultCsvImport>。请注意,这里的想法是,我将IdObj1和IdObj2和IdObj3按3列分组

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.