If you just don't feel like implementing an IEqualityComparer, as Karthik neatly shows you how to do, there is an alternative: you do need to override Equals in your Entity Class:
public class Entity
{
public string ID;
public int Amount;
public Entity(string _ID, int _Amount)
{
ID = _ID; Amount = _Amount;
}
public override bool Equals(object obj)
{
Entity e2 = obj as Entity;
return this.ID == e2.ID && this.Amount == e2.Amount;
}
}
Then you can do this:
List<Entity> E1 = new List<Entity>();
List<Entity> E2 = new List<Entity>();
private void TestListFilteringAndMerging(object sender, EventArgs e)
{
E1.Add(new Entity("A1", 1));
E1.Add(new Entity("A1", 1));
E1.Add(new Entity("B1", 3));
E1.Add(new Entity("C1", 5));
E2.Add(new Entity("A1", 1));
E2.Add(new Entity("D1", 7));
E2.Add(new Entity("F1", 8));
E2.Add(new Entity("F1", 8));
E1 = E1.GroupBy(e1 => e1.ID).Select(e2 => e2.First()).ToList();
E2 = E2.GroupBy(e1 => e1.ID).Select(e2 => e2.First()).ToList();
List<Entity> JoinE1E2 = E1.Concat(E2).GroupBy(e1 => e1.ID).Select(e2 => e2.First()).ToList();
foreach(Entity theEntity in JoinE1E2)
{
Console.WriteLine(theEntity.ID + " : " + theEntity.Amount.ToString());
}
}
However, I'd recommend you go ahead and use the solution Karthik showed you, because: I think it is more readable, probably more maintainable over time ... just all-around more "standard."
I shudder to think of trying to explain the clever use of Linq here ... even to myself :)
And, note that VS 2013 will give you a warning (but not stop compilation) that you have not over-ridden 'GetHashCode.