【问题标题】:Return the indexes of the elements after finding the difference in two lists找到两个列表的差异后返回元素的索引
【发布时间】:2014-06-11 21:27:33
【问题描述】:

我想找出两个字符串列表之间的差异,并返回 list1 中剩余元素的索引(在原始列表中)。

例如,如果 list1 包含“Orange”、“Blue”、“Yellow”,而 list2 包含“Blue”,我可以使用 except 方法轻松获得差异。但是,我想返回索引 - 在这种情况下为 1 和 3。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    请原谅列表创建的懒惰:

    var x = new[] { "Orange", "Blue", "Yellow" }.ToList();
    var y = new[] { "Blue" }.ToList();
    
    var indices = x.Except(y).Select(z => x.IndexOf(z));
    

    这根本不是很有效,但它解决了问题。如果这实际上是为了一些有用的东西而不仅仅是一种心理锻炼,我会重新评估你为什么这样做。

    【讨论】:

    • 你为什么要调用 ToList ?
    • 如果列表不小,这会非常可怕。
    • 数组没有IndexOf 方法。
    • 这是一个可怕的想法,但不确定严格使用 Linq 是否有更好的方法。
    【解决方案2】:
    list1.Select((e,idx) => new { e, idx })
    .Where(x => !list2.Contains(x.e)).Select(x => x.idx);
    

    【讨论】:

    • 像 Jaime 的解决方案一样,这种扩展非常可怕。
    • 您可以将list2 转换为HashSet
    【解决方案3】:

    您可以使用ExceptBy 基于给定项目的投影执行除外,允许您首先将每个集合投影到包含其索引的项目中,然后根据项目本身执行除外:

    var query = first.Select((index, item) => new { index, item })
        .ExceptBy(second.Select((index, item) => new { index, item }),
            pair => pair.item);
    

    public static IEnumerable<TSource> ExceptBy<TSource, TKey>(
        this IEnumerable<TSource> source,
        IEnumerable<TSource> other,
        Func<TSource, TKey> keySelector,
        IEqualityComparer<TKey> comparer = null)
    {
        comparer = comparer ?? EqualityComparer<TKey>.Default;
        var keys = new HashSet<TKey>(other.Select(keySelector), comparer);
        foreach (var item in source)
            if (keys.Add(keySelector(item)))
                yield return item;
    }
    

    【讨论】:

      【解决方案4】:

      解决问题的其他方法:

      var x = new[] { "Orange", "Blue", "Yellow" };
      var y = new HashSet<string>(new[] { "Blue" });
      var indices = Enumerable.Range(0, x.Length)
                              .Where(i => !y.Contains(x[i]))
                              .ToArray();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-16
        • 1970-01-01
        • 2017-05-11
        • 2021-05-19
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多