简体   繁体   English

Linq查询按多列分组但获取其他属性

[英]Linq Query to Group By Multiple Columns But Get Additional Properties

I have a table with many duplicate records. 我有一个包含许多重复记录的表。 How can I use a C# Linq query to group by multiple fields but also get the ID of the distinct record. 如何使用C#Linq查询按多个字段进行分组,还可以获取不同记录的ID。

For example: I have a Store table that looks like this 例如:我有一个看起来像这样的Store表

Store
-----
ID, StoreName, Address1

1, CVS, 123 Main Street
2, CVS, 123 Main Street
3, CVS, 456 Main Street

I want to group by storeName then by address1, but also get the ID of the first distinct (storeName and address1) record. 我想按storeName分组然后按地址1分组,但也获取第一个不同(storeName和address1)记录的ID。

I only want these two records: 我只想要这两个记录:

1, CVS, 123 Main Street
3, CVS, 456 Main Street

I tried using an anonymous object but can't figure out how to get the ID without also grouping by ID. 我尝试使用匿名对象,但无法弄清楚如何获取ID而不按ID分组。

When you use GroupBy in LINQ, you get an enumerable of a class which implements interface IGrouping<TKey,TElement> - the TElement representing the individual, and original, elements that have been grouped. 当您在LINQ中使用GroupBy时,您将获得一个类的枚举,该类实现接口IGrouping<TKey,TElement> - 表示已分组的单个元素和原始元素的TElement

Therefore you would group like so 所以你会这样分组

 var grouped = myList.GroupBy(x => new {x.StoreName,x.Address1});

Which would give you an enumerable list of IGrouping<anonymous,Store> (Assuming the original object was called Store ). 这将为您提供一个可枚举的IGrouping<anonymous,Store> (假设原始对象称为Store )。 The anonymous is an anonymous object with 2 properties StoreName and Address1 . 所述anonymous是有2个属性的匿名对象StoreNameAddress1

Now, each item in the enumerable is itself enumerable of Store , and you can treat that exactly as you would any other enumerable - you can take the First().ID if you wish, and you could project the whole lot back out to an enumerable if thats what you want 现在,枚举中的每个项本身都可以枚举Store ,你可以像对待任何其他枚举一样对待它 - 如果你愿意,可以使用First().ID ,你可以将整个项目投射回一个如果那就是你想要的那么可以枚举

var result = myList.GroupBy(x => new {x.StoreName,x.Address1});
                   .Select(g => new {
                                  g.Key.StoreName, 
                                  g.Key.Address1, 
                                  FirstID = g.First().ID
                                });

Something like this should work. 这样的事情应该有效。 You must apply aggregation on field that is not the part of grouping: 您必须在不属于分组的字段上应用聚合:

var result = list.GroupBy(c => new { c.StoreName, c.Address1 }).
                  Select(c => new
                  {
                      ID = c.Min(i => i.ID),
                      c.Key.StoreName,
                      c.Key.Address1
                  }).ToList();

This is some pseudo code untested but you want something like this 这是一些未经测试的伪代码,但你想要这样的东西

storeList.GroupBy(s => new { s.Storename, s.Address1})
         .SelectMany(g => g.First())
         .ToList()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM