Home > Enterprise >  Check for different specific strings in two-dimensional list
Check for different specific strings in two-dimensional list

Time:09-17

I am trying to check for different strings in a specific dimension and I am curious if it's possible using Linq.

I have two lists with identical structures.

List<List<string>> List1 = new List<List<string>>() {new List<string>() {"ID1", "A"}, 
                                                     new List<string>() {"ID2", "A"}};

List<List<string>> List2 = new List<List<string>>() {new List<string>() {"ID3", "A"}, 
                                                     new List<string>() {"ID4", "B"}};

What I am trying to do is to check for differences between the two nested list's but the problem is I only want to check for differences between nested lists the [1] string.

So.. the expected output for checking for differences between the two mentioned lists would be a list of strings.

{"ID4", "B"}

I've tried using:

IEnumerable<List<string>> ListDiff = List1.Except(List2);

But ListDiff returns every element because of the [0] dimension in the nested list. I want the nested list [0] to be ignored and only check for the [1] (in the nested list).

CodePudding user response:

You can still utilize the Except() function which has an overload that takes an IEqualityComparer<T>. You can implement your own so that it compares the second item in the list, like this:

public class MyListComparer : IEqualityComparer<List<string>>
{
    public bool Equals(List<string> x, List<string> y)
    {
        if (x == null || y == null)
            return false;

        return x[1] == y[1];
    }

    public int GetHashCode(List<string> x)
    {
        if (x == null) return 0;

        return x[1].GetHashCode();
    }
}

Then you'd pass a new instance of this comparer into the Except() function:

List<List<string>> diff = List2.Except(List1, new MyListComparer()).ToList();

This example doesn't handle edge cases where your lists have an amount of items less than or greater than 2. If you need that logic, you can implement that yourself fairly easily in the comparer.

  • Related