[英]FInd matching item in two lists in Entity Framework using Lambda expressions
[英]Intersection of Two lists with index using lambda Expressions
我正在嘗試制作一個包含兩個序列的索引和匹配元素的字典。 例如:-
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表達式來做到這一點。
這樣做,對於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
上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)});
嘗試這個:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.