2014-08-28 108 views
-9

我有2个字符串数组 示例 Main数组包含“ABC”,“DEF”,“GHI”,“TEST”,“TEST”, “ZXY”, “ZXY”, “ZXY”什么是从另一个字符串数组中获取字符串数组索引的最快方法C#

第二个数组包含 “TEST” TEST”, “ZXY”, “ZXY”, “ZXY”

我需要的输出:Get整数数组主要阵列中包含的第二个阵列的指数 这样的 输出是3,4,5,6,7

注意:我需要最快的方法来做到这一点

谢谢:)

+2

'-1'因为零努力。 – 2014-08-28 08:39:52

+0

我无法找到一个方法来做到这一点 – Sumthg 2014-08-28 08:44:08

+0

马可,开始努力工作了,你会如何尝试这个伪代码(提示:for循环和索引),然后翻译成C#代码 – Sayse 2014-08-28 08:44:54

回答

2

也许:

int[] matchingIndices = arr1.Select((str, index) => new { str, index }) 
      .Where(x => arr2.Contains(x.str)) 
      .Select(x => x.index) 
      .ToArray(); 

非LINQ的方式(也许是一点点更有效):

List<int> matchingIndices = new List<int>(arr1.Length); 
for (int i = 0; i < arr1.Length; i++) 
{ 
    if (Array.IndexOf<string>(arr2, arr1[i]) >= 0) 
     matchingIndices.Add(i); 
} 
int[] result = matchingIndices.ToArray(); 
相关问题