开发者

See if item exists once in Enumerable (Linq)

Given a list...

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

etc.

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?


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

Then all you need to call is Union.

var itemUnion = items.Union(listing, new ItemEqualityComparer());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜