tags:

views:

729

answers:

3

In the signature of a method I specify a Func, like so:

public void Method (Func<string, bool> func)

In LINQ, which method (from IEnumerable) will let me pass in a Func from the method parameter to the LINQ query? The other issue is, my func can have any type parameter(s) so the Method from IEnumerable/LINQ must support generic type placeholders.

I want to write something like this:

// Get all elements of type T from the webpage (find is an object in an external API to look for elements in a page).

IEnumerable<T> images = find.GetAllByTagName<T>().All(func);

// Where func is a method parameter which is assigned at run time by the consumer of this API:

public void Test (Func<T, bool> func) { }

How can I best do this? I am on .NET 3.5

Thanks

+1  A: 

Change your API's signature to be open:

public void Method<T> (Predicate<T> func)

Your consumer would close the generic signature with a type T, and supply an appropriate Predicate.

The actual method implementation using LINQ would use Joel's aforementioned Where()

Edit: changed func to predicate

Additional Edit:

I'd personally return an IEnumerable representing your result set constrained by the predicate passed in:

public IEnumerable Method<T> (Predicate<T> func)
{
    return find.Where(func)
}

I'm making some assumptions of what you're trying to do, let me know if this is your intent.

Gurdas Nijor
More readable as public void Method<T> (Predicate<T> func)
recursive
Predicate won't fit in a Where clause, no conversion between Predicate<T> and Func<T, bool>. You could, however, put thePredicate.Invoke inside the Where clause. It will get converted to a Func<T, bool>.
Judah Himango
Interesting, thanks Judah. I thought it'd be a safe assumption that it would work as an implicit cast.
Gurdas Nijor
A: 

In LINQ, which method (from IEnumerable) will let me pass in a Func from the method parameter to the LINQ query?

That question is a little fuzzy to me. If you're looking for a filter algorithm that returns only the matches specified by the Func, use the .Where method:

public void Method (Func<string, bool> func)
{
    return find.GetAllByTagName<T>().Where(func);
}

Does that answer your question? If not, please clarify what you're trying to do.

Judah Himango
I will give this a go when I get on my work machine. I think I rushed the coding due to external pressures (no fault other than mine).
dotnetdev
+1  A: 

In LINQ, which method (from IEnumerable) will let me pass in a Func from the method parameter to the LINQ query?

The extension methods for LinqToObjects hang out on the static System.Linq.Enumerable class.


Given your Func signature, you probably want this overload of Enumerable.Where.

IEnumerable<T> Enumerable.Where<T>(this IEnumerable<T> source, Func<T, bool> filter)

David B
Yep. I saw where but didn't notice the overload (I don't need int). That's why I had the problem at first.
dotnetdev