Question: I have two queries, each one returning a list of objects.

```
List<A> list1 = (....query...)
List<A> list2 = (....query...)

```

"A" is an object model.

Both queries return almost the same objects but with different properties set.

I want to remove duplicates merge them into a single list based on a property of object A.

Basically something like this: 

```
List<A> finalLis = list1 join list2 on elemList1.somePropID == elemList2.somePropID 

```

In simple C# style it would be something like this:

```
foreach(elem1 : list1) {
    foreach(elem2: list1) {
       if(elem1.someID == elem2.someID) {
           elem1.someProp = elem2.someProp
           elem1.otherProp = elem2.otherProp
        }
     }
}

```

I don't want to do it in this way because I'm sure there's a more elegant way in linq.

If you have any suggestions please let me know.

Answer: 
Linq can help you with selecting but not with updating. So you won't get rid of `foreach` statement. So your task could be written with linq like this:

```
//the query is like LEFT JOIN in SQL
var query = from x in list1
            join y in list2 on x.IDItem equals y.IDItem
            into z
            from q in z.DefaultIfEmpty()
            select new {IOne = x, ITwo = q};
foreach (var pair in query)
{
    if (pair.ITwo != null) // && pair.IOne.OneProperty != null
        pair.IOne.OneProperty = pair.ITwo.TwoProperty;
}

var resultList = query.Select(x => x.IOne).ToList();

```

You can check the results [here](http://ideone.com/ecXeXg).
Any solution over `List<T>` will perform at N \* Log(n) at best because the lists need to be sorted.

Implement equality members on your model and use a `HashSet<T>` instead.

This is optimal both in complexity and in allocations.

```
var set1 = new HashSet<Model>
{
    new Model(0, "000"),
    new Model(2, "222"),
    new Model(4, "444"),
};

var set2 = new HashSet<Model>
{
    new Model(1, "111"),
    new Model(2, "2222"),
    new Model(3, "333"),
};

set1.ExceptWith(set2);
set1.UnionWith(set2);

```

To add, it will be faster to use the overwriting set as the result set.

```
set2.UnionWith(set1);

```

Class `Model` in the above sample:

```
class Model
{
    public readonly int Id;
    public string Data;

    public Model(int id, string data)
    {
        Id = id;
        Data = data;
    }

    public override int GetHashCode()
    {
        return Id;
    }

    protected bool Equals(Model other)
    {
        return Id == other.Id;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        return obj.GetType() == GetType() && Equals((Model) obj);
    }
}

```