根据专栏结合两个列表

时间:2013-06-11 20:04:16

标签: c# linq tsql linq-to-sql

我正在使用Linq到Sql的两个列表的联合。使用List1和List2:

 var tr = List1.Union(List2).ToList();

Union工作正常,但问题是检查每一列并删除我想要的一些行。所以我想知道是否有一种方法可以执行基于一列的联合,比如说id,每个列表?

喜欢的东西:

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

这不起作用,但我想知道是否有办法做到这一点,无论是LINQ还是T-SQL

3 个答案:

答案 0 :(得分:4)

你应该使用这个Union()重载(使用自定义相等比较器),或类似的东西:

list1.Concat(list2).GroupBy(x => x.DateProperty).Select(m => m.First());

第一种解决方案肯定更有效率。

答案 1 :(得分:1)

当然,您需要IEqualityComparer个自定义Union。我有一个非常动态,大块代码传入但是:

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

现在,您需要做的就是使用该相等比较器调用Union(使用适合您情况的lambda实例化):

var tr = List1.Union(List2, PropertyEqualityComparer.GetNew(n => n.Id)).ToList();

答案 2 :(得分:0)

试试这个

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

有关详细信息,您可以显示您的模型