Samuel Jackson Samuel Jackson - 23 days ago 6
C# Question

Linq query two arrays for difference based on field comparison

I want to use Linq to compare the values of two Lists based on a different field in each list where the list item values are a string[] array.

The format of the arrays are as follows :

Array 1




  • List

  • 4 fields per
    string[]
    entry



Array 2




  • List

  • 15 fields per
    string[]
    entry



I am trying to compare the value of field 0 from array 1, to check if that value exists in any record in field 12 in array 2, and return the array 1 records where there was no match found in array 2.

What I have so far, is :

var r = array1.Where( p => array2.All( p2 => p2[12] != p[0] ) ).ToList();


This is giving me the following error :


An unhandled exception of type 'System.IndexOutOfRangeException'


How can I make this work ? I know I could do a nested loop O(n)^n, however this is not ideal, which is why I wish to use Linq to compare the sub-values.

Answer

I made an example with your code description, and it works just fine. Can you please check if your array has the correct size?

private static void Main(string[] args)
{
    var array1 = new List<string[]>
    {
        new[] {"1", "2", "3", "4"},
        new[] {"A", "B", "C", "D"}
    };

    var array2 = new List<string[]>
    {
        new[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"},
        new[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}
    };

    var r = array1.Where(p => array2.All(p2 => p2[12] != p[0])).ToList();

    r.ForEach(_ => Array.ForEach(_, Console.WriteLine));

    // output:
    // 1
    // 2
    // 3
    // 4
    // A
    // B
    // C
    // D
}
Comments