打扰一下,请打扰我了。但是我无法提出更简单的方法。
我下课了。
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>
,但是基于FooId
和FooField
的组合,它不应重复。所以我尝试如下
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
添加所有记录,并复制FooId
和FooField
组合,因为CreatedDate
对于所有记录都是唯一的。但是我需要忽略
CreatedDate
并仅添加不违反唯一组合的那些记录。我在这里可以做什么?
Except
? Distinct
?还有其他选择吗?最重要的是,如何?
最佳答案
您要么需要覆盖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/