Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if two lists share values in C#

Tags:

c#-4.0

I'd like to know if two lists share values before applying an intersection. Something like bool DoIntersect(listA, listB) would be fabulous!

This is the code I came up with:

// Person is a class with Id and Name properties
List<Person> people1;
List<Person> people2;

// Populate people1 and people2...

// My current solution (pseudocode obviously)...

if (DoIntersect(people1, people2))
{
    people1 = people1.Intersect(people2)
}
else
{
    /* No shared people */
    throw exception;
}

// Continue with the process...
like image 936
Lenin Avatar asked Sep 12 '25 20:09

Lenin


1 Answers

It depends on exactly what you want:

// are there any common values between a and b?
public static bool SharesAnyValueWith<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
    return a.Intersect(b).Any();
}

For lists that don't overlap, this will iterate through a and b each once. For lists that overlap, this will iterate all the way through a, then through b until the first overlapping element is found.

// does a contain all of b? (ignores duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
    return !b.Except(a).Any();
}

This will iterate through a once, then will iterate through b, stopping on the first element in b not in a.

// does a contain all of b? (considers duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
    // get the count of each distinct element in a
    var counts = a.GroupBy(t => t).ToDictionary(g => g.Key, g => g.Count());
    foreach (var t in b) {
        int count;
        // if t isn't in a or has too few occurrences return false. Otherwise, reduce
        // the count by 1
        if (!counts.TryGetValue(t, out count) || count == 0) { return false; }
        counts[t] = count - 1;
    }

    return true;
}

Similarly, this will iterate through a once, then will iterate through b, stopping on the first element in b not in a.

like image 123
ChaseMedallion Avatar answered Sep 15 '25 22:09

ChaseMedallion