【问题标题】:Intersection of Two lists with index using lambda Expressions使用 lambda 表达式的两个具有索引的列表的交集
【发布时间】:2016-09-01 07:18:36
【问题描述】:

我正在尝试制作一个包含两个序列的索引和匹配元素的字典。 例如:-

List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
List<string> B = new List<string> { "a", "d", "e", "f" };

现在我想构建一个看起来像这样的字典。

// Expected Output:-
// { "a" , 0 }
// { "d" , 3 }
// { "e" , 4 }
// { "f" , 5 }

字典中的第一个条目是两个列表中的公共元素,第二个是第一个列表(A)中的索引。 不确定如何使用 Lambda 表达式来做到这一点。

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

    这样做,对于B 中的每个元素,请使用A 集合中的IndexOf。然后使用ToDictionary 将其转换为你想要的字典形式

    List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
    List<string> B = new List<string> { "a", "d", "e", "f" };
    
     var result = B.Select(item => new { item, Position = A.IndexOf(item) })
                   .ToDictionary(key => key.item, value => value.Position);
    

    请记住,B 中的项目必须是唯一的,才能在 KeyAlreadyExists 上失败。在这种情况下:

     var result = B.Distinct()
                   .Select(item => new { item, Position = A.IndexOf(item) })
                   .ToDictionary(key => key.item, value => value.Position);
    

    如果您不想要未找到项目的结果:

     var result = B.Distinct()
                   .Select(item => new { item, Position = A.IndexOf(item) })
                   .Where(item => item.Position != -1
                   .ToDictionary(key => key.item, value => value.Position);
    

    【讨论】:

    • 注意使用Distinct可能会导致索引的变化。尽管除非 OP 想使用Dictionary&lt;string, List&lt;int&gt;&gt;,否则他必须这样做。
    • @YuvalItzchakov - 我在第二个列表上做不同的,而 indexOf 在第一个列表上 - 所以它不会改变索引
    • OP 已要求两个列表的交集。当我阅读问题时,不能保证B 中的所有元素也存在于A 中(如示例中所示)。要解决这个问题,您必须过滤索引为 &lt; 0 的所有元素。
    • @fknx - 我知道,你是对的,但 OP 也没有解决列表 A 具有超过 1 个值的实例以及要做什么的情况 - 所以我保持它尽可能接近他明确表示并给出了输入/输出:)
    • @GiladGreen 好的,我想这是一个公平的假设:)
    【解决方案2】:

    应该这样做:

    List<string> A = new List<string>{"a","b","c","d","e","f","g"};
    List<string> B = new List<string>{"a","d","e","f"};
    var result = B.ToDictionary(k => k, v => A.IndexOf(b)});
    

    【讨论】:

      【解决方案3】:

      试试这个:

      List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
      List<string> B = new List<string> { "a", "d", "e", "f" };
      
      Dictionary<string, int> result = B.ToDictionary(x => x, x => A.IndexOf(x));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-19
        • 1970-01-01
        • 2017-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多