Taking union of two lists based on column

后端 未结 3 762
渐次进展
渐次进展 2021-01-27 02:41

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

相关标签:
3条回答
  • 2021-01-27 03:14

    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

    0 讨论(0)
  • 2021-01-27 03:16

    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.

    0 讨论(0)
  • 2021-01-27 03:34

    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();
    
    0 讨论(0)
提交回复
热议问题