none
Compare 2 arrays using linq RRS feed

  • Question

  • can anyone tell me how to compare two arrays using LINQ through C# and store the matching values in one array and unmatching values in one array? Thanks in advance.
    Monday, February 5, 2018 6:22 PM

All replies

  • Unfortunately comparison would require that the values in question be comparable. This is generally handled by implementing IEqualityComparer<T>, for equality comparison. Primitives and value types would compare by value but ref types will simply compare object references by default. But assuming you have an IEqualityComparer for your type then you can use Except to get the differences. The Except documentation has an example of comparing 2 Product arrays as an example implementation.

    To get the matches then consider using Intersect which will return only the values that are in both. It has the same example except using Intersect.


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, February 5, 2018 6:32 PM
    Moderator
  • Hello AnkurKumar1610,

    I'm not sure the compare logic. If you want to take the same elements that both array contains. you could try the below example.

     static void Test() {
    
                int[] a= { 1, 2, 3, 4, 5, 6, 7, 8 };
                int[] b= { 2, 4, 6, 7, 9, 0 ,8,56,232,76,1};
    
                List<int> MatchList = new List<int>();
                List<int> UnMatchList = new List<int>();
    
                a.All(i => {
                    if (b.Contains(i)) MatchList.Add(i);
                    else UnMatchList.Add(i);
                    return true;
                });
    
                b.All(j =>
                {
                    {
                        if (!a.Contains(j)) UnMatchList.Add(j);
                        return true;
                    }
                });       
            }

    When the code runs over, the "MatchList" and "UnMatchList" will contains expected result. If you have any issues, please feel free to contact me.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, February 6, 2018 7:38 AM
    Moderator