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

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

问题描述

我有类中的一个列表

 公共类LinqTest
{
公众诠释ID {搞定;组; }
公共字符串值{获得;组; }
}
清单< LinqTest> myList中=新名单< LinqTest>();
myList.Add(新LinqTest(){ID = 1,值=一个});
myList.Add(新LinqTest(){ID = 1,值=B});
myList.Add(新LinqTest(){ID = 2,值=C});

我要只选择不同的ID从该列表。
也就是说,我的结果列表应该只包含

  [{ID = 1,值=A},{n = 2,值=C}]

我怎么能做到这一点的LINQ?

修改

输入,

 值id
1
图1B
2 C
3天
3 C

OUT输出应该是,

 值id
1
2 C
3天

也就是说,如果有 ID ,结果应该采取的第一次出现的重复而已。


解决方案

  myList.GroupBy(测试=> test.id)
      。选择(GRP = GT; grp.First());

编辑:为得到这个的IEnumerable<> 列表与LT;> 似乎是一个谜许多人来说,可以简单的写:

  VAR的结果= myList.GroupBy(测试=> test.id)
                   。选择(GRP => grp.First())
                   .ToList();

但一个是通常能够更好地一起工作的的IEnumerable ,而不是的IList 作为LINQ的上面懒洋洋地评估:它实际上并没有完成所有的工作,直到枚举迭代。当你调用了ToList 它实际上遍历整个枚举迫使所有的工作做在前面。 (可能需要一点,如果你的枚举是无限长的一段时间。)

的反面这个建议是,每次列举这样的时间的IEnumerable 的工作,以评估它必须重新完成。所以,你需要决定每个案例是否是更好地与懒洋洋地评估的IEnumerable 或将它实现成列表设置词典或诸如此类的东西。

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=1,value="a"},{ id = 2, value = "c" }]

How can I do this with 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 occurance only.

解决方案

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:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .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.)

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天全站免登陆