执行 .Distinct() 时忽略匿名类型字符串或 char 成员的大小写

Ignoring casing on anonymous type string or char members when doing .Distinct()

假设我有一个这样的匿名对象列表

list = [{name: "bob"},{name: "sarah"},{name: "Bob"}]

然后当我执行 list.Distinct() 时,我将得到 [{name: "bob"},{name: "sarah"},{name: "Bob"}]

有没有办法告诉它忽略字符串类型成员的大小写,只使用 return bob 或 Bob 作为 duplicate 项目,所以结果是 [{name: "bob"},{name: "sarah"}]

我最好的办法是在 .name.ToLower() 上使用 GroupBy 绕过它 - 但这远非理想。

Distinct使用类型的比较定义来检测相同的对象。这意味着它应该检查它们是否是相同的引用,因为它们是对象。

这可以在https://dotnetfiddle.net/h5AoUZ

中查看

在您的情况下,.NET 无法知道您考虑的标准 bobBob 是相同的。

给你一个建议。带有函数参数的新 Distinct 方法:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

并打电话

list.DistinctBy(x=>x.name.Lower())