1

I have two arrays with same length. for example

arr1 {1,2,3,4,5,6,7,8,9,0}.
arr2 {1,2,5,3,4,6,7,1,1,0}.

I need to get indexes of elements which are different:

{2,3,4,7,8}

How to do this using Linq?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Eugene
  • 127
  • 1
  • 2
  • 8

3 Answers3

4

The simplest I could think of:

int[] diff = Enumerable.Range(0, arr1.Length).Where(i => arr1[i] != arr2[i]).ToArray();
Dennis_E
  • 8,751
  • 23
  • 29
2

This should work:

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();
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

You could use Enumerable.Zip() to walk the arrays in parallel, compare the values, then output matching sequence indices:

        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]

This doesn't require the sequences to be arrays.

dbc
  • 104,963
  • 20
  • 228
  • 340