tags:

views:

81

answers:

1

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?

+3  A: 

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());
ChaosPandion
I'm not sure, but I think OP wants something more like a set-difference (`Except`) than a `Union`.
tzaman
This isn't the specific problem I am having, but it was very useful and solved a different part of the problem. I am opening another question with much more specifics and I will be editing my phrasing in this one to relate to the answer; since it is still useful.
Stacey