I am taking a union of two lists using Linq to Sql. Using List1 and List2:
var tr = List1.Union(List2).ToList();
Union works fine, but the pro
try somthing this
var List3 = List1.Join(
List2,
l1 => l1.Id,
l2 => l2.Id,
(l1, l2) => new Model
{
Id = l1.Id,
Val1 = l1.Val1 or other,
Val2 = l2.Val2 or other
});
for more details you can show your model
You should use this Union() overload (with a custom equality comparer) , or something like this:
list1.Concat(list2).GroupBy(x => x.DateProperty).Select(m => m.First());
The first solution is certainly more efficient.
Sure, you need a custom IEqualityComparer
with Union
. I have one that's really dynamic, big block of code incoming though:
public class PropertyEqualityComparer<TObject, TProperty>
: IEqualityComparer<TObject>
{
Func<TObject, TProperty> _selector;
IEqualityComparer<TProperty> _internalComparer;
public PropertyEqualityComparer(Func<TObject, TProperty> propertySelector,
IEqualityComparer<TProperty> innerEqualityComparer = null)
{
_selector = propertySelector;
_internalComparer = innerEqualityComparer;
}
public int GetHashCode(TObject obj)
{
return _selector(obj).GetHashCode();
}
public bool Equals(TObject x, TObject y)
{
IEqualityComparer<TProperty> comparer =
_internalComparer ?? EqualityComparer<TProperty>.Default;
return comparer.Equals(_selector(x), _selector(y));
}
}
public static class PropertyEqualityComparer
{
public static PropertyEqualityComparer<TObject, TProperty>
GetNew<TObject, TProperty>(Func<TObject, TProperty> propertySelector)
{
return new PropertyEqualityComparer<TObject, TProperty>
(propertySelector);
}
public static PropertyEqualityComparer<TObject, TProperty>
GetNew<TObject, TProperty>
(Func<TObject, TProperty> propertySelector,
IEqualityComparer<TProperty> comparer)
{
return new PropertyEqualityComparer<TObject, TProperty>
(propertySelector, comparer);
}
}
Now, all you need to do is call Union with that equality comparer (instantiated with a lambda that fits your circumstance):
var tr = List1.Union(List2, PropertyEqualityComparer.GetNew(n => n.Id)).ToList();