C# 使用 linq 选择不同的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19406242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:54:58  来源:igfitidea点击:

Select distinct using linq

c#linqlistclass

提问by Anoop Joshi

I have a class list of class

我有一个班级列表

public class LinqTest
{
public int id { get; set; }
public string value { get; set; }
}


List<LinqTest> myList = new List<LinqTest>();
myList.Add(new LinqTest() { id = 1, value = "a" });
myList.Add(new LinqTest() { id = 1, value = "b" });
myList.Add(new LinqTest() { id = 2, value = "c" });

I need to select only the distinct id's from that list. ie, my resultant list should only contain

我只需要从该列表中选择不同的 id。即,我的结果列表应该只包含

[{id=1,value="a"},{ id = 2, value = "c" }]

How can I do this with linq?

我怎样才能用 linq 做到这一点?

Edit

编辑

Input,

输入,

id      value
1        a
1        b
2        c
3        d
3        e

Out put should be,

输出应该是,

id      value
1        a
2        c
3        d

ie, if there is a repetition of id, result should take the first occurrence only.

即,如果 重复id,则结果应仅出现第一次。

采纳答案by Paul Ruane

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<>into a List<>seems to be a mystery to many people, you can simply write:

编辑:对于很多人来说,把它IEnumerable<>变成一个List<>似乎是个谜,你可以简单地写:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerablerather than IListas the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToListit actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

但是通常最好使用IEnumerable而不是IList因为上面的 Linq 被懒惰地评估:在迭代可枚举之前,它实际上并没有完成所有工作。当您调用ToList它时,它实际上会遍历整个可枚举对象,从而强制预先完成所有工作。(如果您的可枚举数无限长,则可能需要一段时间。)

The flipside to this advice is that each time you enumerate such an IEnumerablethe work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerableor to realize it into a List, Set, Dictionaryor whatnot.

这个建议的另一面是,每次你枚举这样一个IEnumerable评估它的工作都必须重新完成。所以,你需要决定每个案例是否是更好的工作与评估懒洋洋地IEnumerable或将其实现为ListSetDictionary或诸如此类的东西。

回答by Daniel Hilgarth

Using morelinqyou can use DistinctBy:

使用morelinq您可以使用DistinctBy

myList.DistinctBy(x => x.id);

Otherwise, you can use a group:

否则,您可以使用组:

myList.GroupBy(x => x.id)
      .Select(g => g.First());

回答by Tim Rogers

myList.GroupBy(i => i.id).Select(group => group.First())

回答by Tim Schmelter

You should override Equalsand GetHashCodemeaningfully, in this case to compare the ID:

在这种情况下,您应该有意义地覆盖EqualsGetHashCode比较 ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

现在您可以使用Distinct

List<LinqTest> uniqueIDs = myList.Distinct().ToList();