2016-03-04 36 views
1

我有兩個list<int>類型的列表,我知道我們可以找到兩個列表之間的公共元素。但是有沒有什麼辦法可以在相交列表中獲取常用元素和相應的常用元素索引,或者我需要遍歷每個元素找到索引。從兩個列表中獲取具有索引的常用元素C#

+0

你能告訴你的代碼,也表明一個例子嗎? –

+0

你嘗試過什麼嗎?你當然可以用LINQ來做這件事,儘管我懷疑它的代碼和沒有代碼一樣多。 –

+0

現在有兩個答案,其中一個只在值相同時才匹配*和*索引相同,其中一個只與值匹配(給每個匹配提供兩個索引)。你想要什麼? –

回答

4

LINQ有使用索引投影序列的操作,但是這並沒有內置到查詢表達式語法中,因此您必須使用「常規」擴展方法調用來啓動。之後,它是相當容易的,雖然可能只是簡單不使用LINQ,說實話:

var pairs1 = list1.Select((value, index) => new { value, index }); 
var pairs2 = list2.Select((value, index) => new { value, index }); 
var matches = from pair1 in pairs1 
       join pair2 in pairs2 on pair1.value equals pair2.value 
       select new 
       { 
        Value = pair1.value, 
        Index1 = pair1.index, 
        Index2 = pair2.index 
       }; 

(你可以使用from pair2 in pairs2 where pair1.value == pair2.value如果你願意......)

或非LINQ(使用Tuple<,,>爲簡單起見,其他的選項是可行的):

var results = new List<Tuple<int, int, int>>(); 
for (int index1 = 0; index1 < list1.Count; index1++) 
{ 
    for (int index2 = 0; index2 < list2.Count; index2++) 
    { 
     if (list1[index1] == list2[index2]) 
     { 
      results.Add(Tuple.Of(list1[index1], index1, index2); 
     } 
    } 
} 

注意,不同於一般的交集操作,這兩個可以給你相同的值的多個結果 - 因爲可以有多個索引對。例如,對於列表{ 1, 2 }{2, 2, 0},您將擁有(值= 2,索引1 = 1,索引2 = 0),(值= 2,索引1 = 1,索引2 = 1)的元組。

+0

我剛剛使用這個答案從一個json字符串中創建一個新的對象,我從一個節點rest api消耗。這太棒了。再次感謝您節省@Jon Skeet的一天! –

0

試試下面的代碼

List<int> lstA = new List<int>() { 10, 2, 7, 9, 13, 21, 17 }; 
List<int> lstB = new List<int>() { 2, 10, 7, 21, 13, 9, 17 }; 

var lstA_Temp = lstA.Select((value, index) => new { index, value }).ToList(); 
var lstB_Temp = lstB.Select((value, index) => new { index, value }).ToList(); 


List<int> result = (from A in lstA_Temp from B in lstB_Temp 
        where A.index == B.index where A.value == B.value 
        select A.value).ToList(); 

你也可以做這件事而不LINQ見下面的邏輯

List<int> lstA = new List<int>() { 10, 2, 7, 9, 13, 21, 17 }; 
List<int> lstB = new List<int>() { 2, 10, 7, 21, 13, 9, 17 }; 

List<int> lstResult = new List<int>(); 

for (int i = 0; i < lstA.Count; i++) 
{ 
    if (lstA[i] == lstB[i]) 
     lstResult.Add(lstA[i]); 
} 
+0

請注意,如果您在索引上匹配,則使用'Zip' IMO會更簡單。 –

相關問題