在使用LINQ列表中删除重复项 [英] removing duplicates in a list with linq

查看:123
本文介绍了在使用LINQ列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个像这样为MyObject的列表:

Suppose you have a list of MyObject like this:

public class MyObject
{
  public int ObjectID {get;set;}
  public string Prop1 {get;set;}
}

如何从一个列表,其中有可能是用同样的ObjectID对象的多个实例,删除重复。

How do you remove duplicates from a list where there could be multiple instance of objects with the same ObjectID.

感谢。

推荐答案

您可以使用 GROUPBY()并选择每个组的第一项来实现你想要的 - 假设你要选择一个项目为每个不同的的ObjectId 属性:

You can use GroupBy() and select the first item of each group to achieve what you want - assuming you want to pick one item for each distinct ObjectId property:

var distinctList = myList.GroupBy(x => x.ObjectID)
                         .Select(g => g.First())
                         .ToList();



另外还有的 DistinctBy() 中的 moreLinq项目,将允许进行更简洁的语法(但会增加依赖到项目):

Alternatively there is also DistinctBy() in the MoreLinq project that would allow for a more concise syntax (but would add a dependency to your project):

var distinctList = myList.DistinctBy( x => x.ObjectID).ToList();

这篇关于在使用LINQ列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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