Is there a way to parameterize the Contains portion of Linq when linked to an array

Viewed 65

Is there a way to parameterize the Contains portion of Linq when linked to an array.

I have the following code.

var query = Data.Where(s => an_array.Contains(s.Name)).Distinct().ToList();

How can I parameterize s.Name so I can create a method that uses a func or something else?

I am used to using (Func<Model, T> param ) and using it in linq where the input looks like (s=>s.Name), but I am stuck because the Contains portion is just looking for (s.Name)

I have tried using (Func<Model, string> param ) but that doesn't seem right.

Thanks!

Update 1:

If I have a method like below, where s.Name changes depending on user input. How can I pass that to the method.

public void GetFilteredItems()
{
 var queryresult = Data.Where(s => an_array.Contains(s.Name)).Distinct().ToList();
}

Ideally would like something like this so it will work with whatever is passed.

public void GetFilteredItems(Func<?,?> param)
{
 var queryresult = Data.Where(s => an_array.Contains(param)).Distinct().ToList();
}
2 Answers

Is this what you want?

Func<Model, string> p = s => s.Name;

var query = Data.Where(s => an_array.Contains(p(s))).Distinct().ToList();

I think what you want is Any, rather than Contains. One of the overloads takes a predicate that you can use to test for a specific condition:

public void GetFilteredItems<T>(Func<T, bool> predicate)
{
    var queryresult = Data.Where(s => an_array.Any(predicate)).Distinct().ToList();
}
Related