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

Dev*_*avi 1 .net c# 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; }
}
Run Code Online (Sandbox Code Playgroud)

我需要遍历的东西,并添加了一系列FooList<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));
}
Run Code Online (Sandbox Code Playgroud)

Except中心将所有的记录和复制的FooIdFooField组合CreatedDate将是所有独特记录.

但我需要忽略它CreatedDate,只需添加那些不违反唯一组合的记录.

我能在这做什么?ExceptDistinct?还有其他选择吗?

最重要的是,怎么样?

Jon*_*eet 7

你要么需要重写EqualsFoo,或实现的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

 foos.AddRange(processedFoos.Except(foos, new FooComparer()));
Run Code Online (Sandbox Code Playgroud)