使用 linq 选择不同的 [英] Select distinct using linq

查看:21
本文介绍了使用 linq 选择不同的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级列表

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

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

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

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

如何使用 linq 执行此操作?

How can I do this with linq?

编辑

输入,

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

输出应该是,

id      value
1        a
2        c
3        d

即,如果id有重复,结果应该只出现在第一次.

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

推荐答案

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

将这个 IEnumerable<> 放入 List<> 似乎对很多人来说是个谜,你可以简单地写:

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

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

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

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it 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 时,必须重新进行评估它的工作.因此,您需要针对每种情况决定是使用惰性求值的 IEnumerable 还是将其实现为 ListSet字典或者诸如此类.

The flipside to this advice is that each time you enumerate such an IEnumerable the 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 IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

这篇关于使用 linq 选择不同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆