How to get items that are and are not on the list

I have IEnumerable, listOfOnes and IEnumerable, listOfTwos.

Assuming I can compare V objects with T objects, I would like to find which elements are in listOfOnes, but not in listOfTwos. And vice versa.

Example:

        var listOfOnes = new List<One>
        {
            new One
            {
                name = "chris",
                type = "user"
            },
            new One
            {
                name = "foo",
                type = "group"
            },
            new One
            {
                name = "john",
                type = "user"
            },
        };

        var listOfTwos = new[]
        {
            new Two
            {
                name = "chris",
                type = "user"
            },
            new Two
            {
                name = "john",
                type = "user"
            },
            new Two
            {
                name = "the Steves",
                type = "group"
            }
        };


        var notInTwos; //= listOfOnes.FindDifferences(listOfTwos); 
        //find all objects not in listOfTwos. Should find 'foo'.

        var notInOnes; //= listOfTwos.FindDifferences(listOfOnes)
        //find all objects not in listOfOnes. Should find 'the Steves'.
+3
source share
2 answers

If you can convert one type to another, you can use Except and Intersect , for example:

listOfOnes.Except(listOfTwos.Cast<One>())

Otherwise, you can check for each element in the first list if it is equal to any of the elements in the second list:

var notInTwos = listOfOnes.Where(one =>
    !listOfTwos.Any(two => two.Equals(one)));

It will not be so fast though.

+6
source

Maybe something like

public static IEnumerable<T> FindDifference<U> (
    this IEnumerable<T> a, 
    IEnumerable<U> b,
    Func<T, U> convert)
{
    IEnumerable<T> bConvertedToT = b.Select (item => convert (item));
    IEnumerable<T> aNotInB = a.Except (bConvertedToT);
    return aNotInB;
}
+1

Source: https://habr.com/ru/post/1740218/


All Articles