【问题标题】:Ignoring casing on anonymous type string or char members when doing .Distinct()执行 .Distinct() 时忽略匿名类型字符串或字符成员的大小写
【发布时间】:2018-07-18 21:45:55
【问题描述】:

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

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

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

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

我最好的办法是在.name.ToLower() 上使用GroupBy 来破解它——但这远非理想。

【问题讨论】:

    标签: c# linq distinct


    【解决方案1】:

    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())
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 2013-04-11
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多