代码之家  ›  专栏  ›  技术社区  ›  Matt

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

  •  0
  • Matt  · 技术社区  · 7 年前

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

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

    那么当我做list.distinct()时,我将得到 [{name: "bob"},{name: "sarah"},{name: "Bob"}]

    是否有方法告诉它忽略字符串类型成员上的大小写,并让它返回bob或bob 复制 所以结果是 [{name: "bob"},{name: "sarah"}]

    我最好的办法就是用 GroupBy .name.ToLower() -但这远不是理想。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Antoine V    7 年前

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

    可以办理入住手续 https://dotnetfiddle.net/h5AoUZ

    在您的情况下,.net无法知道您需要考虑的标准 bob Bob 都一样。

    给你一个建议带有函数参数的新的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())