我在 C# 中有一个对象列表<>,我需要一种方法来返回那些在列表中被认为是重复的对象。我不需要 Distinct 结果集,我需要一个我将从存储库中删除的项目的列表。
为了这个例子,假设我有一个“汽车”类型的列表,我需要知道这些汽车中有哪些与列表中的其他汽车颜色相同。以下是列表中的汽车及其颜色属性:
Car1.Color = Red;
Car2.Color = Blue;
Car3.Color = Green;
Car4.Color = Red;
Car5.Color = Red;
对于这个例子,我需要结果(IEnumerable<>、List<> 或其他)来包含 Car4 和 Car5,因为我想从我的存储库或数据库中删除它们,这样我的存储库中每种颜色只有一辆车.任何帮助将不胜感激。
最佳答案
我昨天无意中编写了这个代码,当时我正在尝试编写一个“不同的投影”。我包括了一个!当我不应该的时候,但这次恰到好处:
public static IEnumerable<TSource> DuplicatesBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
// Yield it if the key hasn't actually been added - i.e. it
// was already in the set
if (!seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
然后你会调用它:
var duplicates = cars.DuplicatesBy(car => car.Color);
关于C# 3.0 : Need to return duplicates from a List<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/493673/