看看项可枚举存在一次(LINQ) [英] See if item exists once in Enumerable (Linq)
本文介绍了看看项可枚举存在一次(LINQ)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个列表...
class Item
{
public Name
{
get;
set;
}
}
List<Item> items = new List<Item>
{
new Item() { Name = "Item 1" },
new Item() { Name = "Item 1" },
new Item() { Name = "Item 2" },
new Item() { Name = "Item 3" }
}
List<Item> listing = new List<Item>
{
new Item() { Name = "Item 1" },
new Item() { Name = "Item 2" },
new Item() { Name = "Item 3" }
new Item() { Name = "Item 4" }
}
等
我需要创建一个第三个数组,将抵消这两者之间的双实例;然而与名称1的项目都是一样的,但不同的实例。所以第三个列表应该有1项第1例中,由于'项目'有2个实例。这是如何通过LINQ的做任何想法?
I need to create a third array that will cancel out double instances between the two; however items with "Name 1" are both the same, but different 'instances'. So the third List should have 1 instance of Item 1, since 'items' had 2 instances. Any ideas of how this can be done through Linq?
推荐答案
首先,你需要创建一个 EqualityComparer
为项目
。
First you need to create an EqualityComparer
for Item
.
public sealed class ItemEqualityComparer : EqualityComparer<Item>
{
public override bool Equals(Item x, Item y)
{
return x.Name.CompareTo(y.Name) == 0;
}
public override int GetHashCode(Item obj)
{
return obj.Name.GetHashCode();
}
}
然后你需要调用是<$ C $ 。C>联盟
var itemUnion = items.Union(listing, new ItemEqualityComparer());
这篇关于看看项可枚举存在一次(LINQ)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文