Taking union of two lists based on column

2019-03-04 22:53发布

问题:

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 problem is it is checking each column and removes some of the rows that I want. So I was wondering if there is a a way I can perform a union based on one column only, like let's say id, of each list?

Something Like:

var t = List1.id.Union(List2.id).ToList();

This doesn't work, but I was wondering if there is a way to do this, either with LINQ or T-SQL

回答1:

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.



回答2:

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


回答3:

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