使用lambda表达式的两个列表与索引的交集

本文关键字:列表 索引 两个 表达式 lambda 使用 | 更新日期: 2023-09-27 18:05:01

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

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表达式来做到这一点。

使用lambda表达式的两个列表与索引的交集

这样做,对于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);

应该这样做:

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)});

try this:

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