C# 使用lambda表达式将两个列表与索引相交

C# 使用lambda表达式将两个列表与索引相交,c#,linq,dictionary,C#,Linq,Dictionary,我试图制作一个包含两个序列的索引和匹配元素的字典。 例如:- List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" }; List<string> B = new List<string> { "a", "d", "e", "f" }; 其中,字典中的第一个条目是两个列表中的公共元素,第二个条目是第一个列表(A)中的索引。 不确定如何表达Lambda表达式来实现

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

List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
List<string> B = new List<string> { "a", "d", "e", "f" };
其中,字典中的第一个条目是两个列表中的公共元素,第二个条目是第一个列表(A)中的索引。
不确定如何表达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);
如果不希望找到未找到的项目的结果,请执行以下操作:

 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)});
List A=新列表{“A”、“b”、“c”、“d”、“e”、“f”、“g”};
列表B=新列表{“a”、“d”、“e”、“f”};
var result=B.ToDictionary(k=>k,v=>A.IndexOf(B)});
试试这个:

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));
List A=新列表{“A”、“b”、“c”、“d”、“e”、“f”、“g”};
列表B=新列表{“a”、“d”、“e”、“f”};
字典结果=B.ToDictionary(x=>x,x=>A.IndexOf(x));

请注意,使用
Distinct
可能会导致索引的更改。虽然除非OP想使用
字典
,否则他必须这样做。@YuvalItzchakov-我在第二个列表上做distinct,而indexOf在第一个列表上-因此它不会更改索引OP要求两个列表的交叉点。当我阅读问题时,不能保证
B
中的所有元素也出现在
A
中(如示例所示)。要解决这个问题,你必须用索引
<0
@fknx筛选所有元素-我知道,你是对的,但OP也没有解决列表A有一个以上的值实例的情况,以及要做什么-所以我尽量接近他明确说的内容,并给出输入/输出:)@GiladGreen好的,我想这是一个合理的假设:)
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)});
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));