从C#中的列表中删除重复项 [英] remove duplicate items from list in c#
本文介绍了从C#中的列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类型类别的列表
public class MyClass
{
public SomeOtherClass classObj;
public string BillId;
}
public List<MyClass> myClassObject;
样本值:
BillId = "123",classObj = {},
BillId = "999",classObj = {},
BillId = "777",classObj = {},
BillId = "123",classObj = {}
因此在上面的示例中,我们有 BillId
的重复值.我想删除所有重复的值(不重复),以便结果仅包含 999
& 777
值.
So in above example, we have duplicate values for BillId
. I would like to remove all the duplicate values (Not Distinct) so the result would contain only 999
& 777
value.
实现此目标的一种方法
- 遍历所有项目
- 获取唯一的
BillId
的计数 - 如果count大于1,则将该
BillId
存储在另一个变量中 - 再次循环并根据
BillId
删除项目
- Loop through all items
- Get count of unique
BillId
- If count is greater than 1, store that
BillId
in another variable - Loop again and remove item based on
BillId
有没有简单的方法可以实现这一目标?
Is there any straightforward way to achieve this?
推荐答案
我认为这可行:
var result = myClassObject.GroupBy(x => x.BillId)
.Where(x => x.Count() == 1)
.Select(x => x.First());
小提琴此处
这篇关于从C#中的列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文