user2436996
user2436996

Reputation: 181

Compare 2 lists, specifying the selectors as parameters

I have the following function

public static class ListUtils
{
    public static bool ListsHaveCommonality<T>(List<T> listOne, List<T> listTwo, Func<T, string> selectorOne, Func<T, string> selectorTwo)
    {
    return listOne.Select(selectorOne).Intersect(listTwo.Select(selectorTwo)).Any();
    }
}

Then a test to check it works

//Arrange
List<Alias> aliases = new List<Alias>();
Alias a1 = new Alias { alias = "[email protected]" };
Alias a2 = new Alias { alias = "[email protected]" };
Alias a3 = new Alias { alias = "[email protected]" };

aliases.Add(a1);
aliases.Add(a2);
aliases.Add(a3);

List<string> chosenAliases = new List<string>
            {
                "[email protected]",
                "[email protected]",
            };

//Act
bool hasCommonality = ListUtils.ListsHaveCommonality(aliases, chosenAliases, (Alias a) => a.alias, (string s) => s);

//Assert
Assert.IsTrue(hasCommonality);

I get the following error

The type arguments for method System.Func, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Upvotes: 0

Views: 36

Answers (2)

Eli
Eli

Reputation: 693

listOne and listTwo are both defined as List<T>, but for the first you are sending List<Alias> and for the second you are sending List<string>.

Upvotes: 0

Yacoub Massad
Yacoub Massad

Reputation: 27861

ListsHaveCommonality assumes that both lists have the same type parameter T. If you want to use it with lists that have different item types, you need to create a method that supports two type parameters like this:

public static class ListUtils
{
    public static bool ListsHaveCommonality<T1,T2>(
        List<T1> listOne,
        List<T2> listTwo,
        Func<T1, string> selectorOne,
        Func<T2, string> selectorTwo)
    {
        return listOne.Select(selectorOne).Intersect(listTwo.Select(selectorTwo)).Any();
    }
}

Upvotes: 1

Related Questions