LINQ在类项目上的区别?[英] LINQ distinct on class item?

本文是小编为大家收集整理的关于LINQ在类项目上的区别?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

请注意,此问题相似这个除了我不使用linq to-sql,因此" let"不可用.

基本上我选择了类型

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name }).Distinct().ToList()

我刚有

时曾经工作
... .Select(c => c.Location.Name).Distinct().ToList()

如何对SampleClass中的一个项目进行独特的呼吁?

推荐答案

您可以按密钥对项目进行分组,然后选择要用作值的组中的项目.我以FirstOrDefault为例:

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name })
    .GroupBy(c => c.Id)
    .Select(group => group.FirstOrDefault())
    .ToList()

其他推荐答案

这是您需要的: blogspot.com/2009/11/convenient-distinct.html ?

这是iEnumerable的扩展程序,允许您为任何字段(甚至是使用Lambdas的几个字段).

本文地址:https://www.itbaoku.cn/post/1556777.html

问题描述

Note this question is similar this one except I'm not working with linq-to-sql, so the "let" is not usable.

Basically I have a select of the type

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name }).Distinct().ToList()

which used to work when I just had

... .Select(c => c.Location.Name).Distinct().ToList()

How would I make a distinct call on one of the items within the SampleClass?

推荐答案

You can group items by the key, and then select what item from the group you want to use as value. I use FirstOrDefault as an example:

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name })
    .GroupBy(c => c.Id)
    .Select(group => group.FirstOrDefault())
    .ToList()

其他推荐答案

Is this what you need: http://sprokhorenko.blogspot.com/2009/11/convenient-distinct.html ?

This is an extension for IEnumerable that allows you to .Distinct() for any field (or even several ones using lambdas), which creates IEqualityComparer for you on the fly.