[英]How to use LINQ Group Records and use Distinct
given this Records鉴于此记录
class Record
{
DateTime Date {get; set;}
string Article {get; set;}
string Platform { get; set;}
string Amount { get; set;}
}
With a sql query I get a list of Records and want to Group the Platforms by Article.通过 sql 查询,我得到了一个记录列表,并希望按文章对平台进行分组。
I do this query:我做这个查询:
List<Record> recordList = FetchRecords();
var group = recordList.GroupBy(
f => f.Article,
(key, g) => new
{
Article= key,
Platforms = g.Select(p => p.Platform).ToList()
});
There are around 120 different Articles and about 30 different platforms, so the expected amount of items in group is around 120 yet I am recieving thousands of items.大约有 120 种不同的文章和大约 30 种不同的平台,因此组中的预期物品数量约为 120 件,但我收到了数千件物品。 Items in record list are a lot as its the stock of all articles in the last 30 Days so I want to get a distinct list of Articles.
记录列表中的项目很多,因为它是过去 30 天内所有文章的库存,所以我想获得一个独特的文章列表。 I just can't figure out where to do this.
我只是想不出在哪里做这个。 what am I missing?
我错过了什么?
Edit :编辑:
After further inspecting the Data at runtime I just noticed that I have it backwards.在运行时进一步检查数据后,我发现我把它倒过来了。 the Articles are already correctly grouped, the platforms are the ones that need to be distinct, like Astrid E was guessing in the comments
文章已经正确分组,平台是需要区分的平台,就像 Astrid E 在评论中猜测的那样
You can return distinct values of the Platform
collection by using Enumerable.Distinct()
.您可以使用
Enumerable.Distinct()
返回Platform
集合的不同值。
The Platforms
value in the result selector in your .GroupBy()
operation should be computed as follows: .GroupBy()
操作中结果选择器中的Platforms
值应按如下方式计算:
Platforms = g.Select(p => p.Platform).Distinct().ToList()
Maybe you could try something like this:也许你可以尝试这样的事情:
var group = recordList.GroupBy(r => r.Article)
.Select(a =>
new
{
Article = a.Key,
Platforms = a.GroupBy(g => g.Platform)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.