2016-03-04 38 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会更简单。 –

相关问题