2

我正在使用 Linq to Sql 合并两个列表。使用 List1 和 List2:

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

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

就像是:

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

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

4

4 回答 4

5

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

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

第一个解决方案当然更有效。

于 2013-06-11T20:13:30.083 回答
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();
于 2013-06-11T20:16:31.317 回答
0

尝试这个:

var merged = new List<Person>(list1);
merged.AddRange(list2.Where(p2 => 
                list1.All(p1 => p1.Id != p2.Id)));
于 2021-11-01T09:56:08.380 回答
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
});

有关更多详细信息,您可以展示您的模型

于 2018-02-08T10:57:07.313 回答