我有两个长度相同的数组。例如
arr1 {1,2,3,4,5,6,7,8,9,0}.
arr2 {1,2,5,3,4,6,7,1,1,0}.
我需要得到不同元素的索引:
{2,3,4,7,8}
如何使用Linq执行此操作?
答案 0 :(得分:4)
我能想到的最简单:
int[] diff = Enumerable.Range(0, arr1.Length).Where(i => arr1[i] != arr2[i]).ToArray();
答案 1 :(得分:2)
这应该有效:
int[] arr1 = new[] {1,2,3,4,5,6,7,8,9,0};
int[] arr2 = new[] {1,2,5,3,4,6,7,1,1,0};
var differentIndexes = arr2.Select((item, index) => new { item, index })
.Where(x => x.item != arr1[x.index])
.Select(x => x.index)
.ToArray();
答案 2 :(得分:1)
您可以使用Enumerable.Zip()
并行遍历数组,比较值,然后输出匹配的序列索引:
int [] arr1 = new int [] {1,2,3,4,5,6,7,8,9,0};
int [] arr2 = new int [] {1,2,5,3,4,6,7,1,1,0};
var query = arr1.Zip(arr2, (i, j) => i != j).Select((b, i) => b ? (int?)i : null).Where(iptr => iptr.HasValue).Select(iptr => (int)iptr);
Debug.WriteLine(JsonConvert.SerializeObject(query.ToList())); // outputs [2,3,4,7,8]
这并不要求序列是数组。