c# - LINQ Except/Distinct仅基于少数列,不添加重复项

标签 c# .net linq distinct except

打扰一下,请打扰我了。但是我无法提出更简单的方法。

我下课了。

public class Foo
{
    public FooId int { get; set; }

    public FooField string { get; set; }

    //some more fields here....
    //....
    //....

    public DateTime CreatedDate { get; set; }
}


我需要遍历某些东西,并在Foo中添加一个范围List<Foo>,但是基于FooIdFooField的组合,它不应重复。

所以我尝试如下

List<Foo> foos = new List<Foo>();

foreach (Bar item in blah.Bars)
{
    //Some code here to get the foos from the item
    List<Foo> processedFoos = item.GetFoos();

    //The problem is with below line
    foos.AddRange(processedFoos.Except(foos));
}


Except添加所有记录,并复制FooIdFooField组合,因为CreatedDate对于所有记录都是唯一的。

但是我需要忽略CreatedDate并仅添加不违反唯一组合的那些记录。

我在这里可以做什么? ExceptDistinct?还有其他选择吗?

最重要的是,如何?

最佳答案

您要么需要覆盖Equals中的Foo,要么实现一个IEqualityComparer<Foo>,以便Except可以知道两个Foo值何时相等。例如:

public sealed class FooComparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo x, Foo y)
    {
        return x.FooId == y.FooId && x.FooField == y.FooField;
    }

    public int GetHashCode(Foo foo)
    {
        // Note that if FooField can be null, you'll need to account for that...
        return foo.FooId ^ foo.FooField.GetHashCode();
    }
}


然后:

 foos.AddRange(processedFoos.Except(foos, new FooComparer()));

关于c# - LINQ Except/Distinct仅基于少数列,不添加重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30727592/

相关文章:

c# - 如果类型相同,Array.ToArray<>() 是否返回原始数组?

c# - 使用 Select(...).Any(...) 时,select 的方法运行了多少次?

c# - 字幕仅适用于全屏

.net - 视觉 C++ 2005 'Ports' : is not a member of 'System::IO'

c# - 如何使用 LINQ 对对象集合进行简单的基于顺序的验证?

c# - 如何通过几个点绘制贝塞尔曲线?

.net - SQL Server CLR 函数

c# - 说明静态成员

c# - 我需要知道如何将特定的 XML 反序列化为 C# 中自定义类中定义的对象

C# 联合和数组复制