【发布时间】:2015-02-20 17:27:07
【问题描述】:
我有一个对象列表。这些对象有一个属性,例如“价值”。
var lst = new List<TestNode>();
var c1 = new TestNode()
{
Value = "A",
};
lst.Add(c1);
var c2 = new TestNode()
{
Value = "A",
};
lst.Add(c2);
var c3 = new TestNode()
{
Value = "B",
};
lst.Add(c3);
var c4 = new TestNode()
{
Value = "B",
};
lst.Add(c4);
我想说的是:
lst.PartialDistinct(x => x.Value == "A")
这只能通过谓词来区分,并且在打印结果 IEnumerable 的“值”时,结果应该是:
A
B
B
我已经找到了可以定义 Key-Selector 的 DistinctBy 解决方案。但结果当然是:
A
B
Cyral 的第一个答案完成了这项工作。所以我接受了。但 Scott 的回答确实是一个 PartialDistinct() 方法,看起来它解决了我所有的问题。
好的,我以为 Scott 的解决方案已经解决了,但事实并非如此。也许我在单元测试时犯了一个错误……或者我不知道。问题是:
if(seen.Add(item))
这不会过滤掉其他值为“A”的对象。我认为这是因为它在放入 hashset 时依赖于引用相等。
我最终得到了以下解决方案:
public static IEnumerable<T> PartialDistinct<T>(this IEnumerable<T> source Func<T, bool> predicate)
{
return source
.Where(predicate)
.Take(1)
.Concat(source.Where(x => !predicate(x)));
}
【问题讨论】:
-
有
TestNode其他属性吗?剩下的单个对象的这些属性的值应该是多少? -
您是要在
Value上执行不同的操作,还是在TestNodewhereValue == A加上正常的结果集 whereValue != A上执行不同的操作?