Ruhrpottpatriot
Ruhrpottpatriot

Reputation: 1068

Pass LINQ query to method to select dynamically form collection

I already looked up on the question on SO, but couldn't find a solution for my problem.

In my program is a class whose sole reason is selecting from a collection of data passed to it via constructor. What I need to to is pass a LINQ query to the selecting method to select from said data. However I have no luck solving my problem. Here is the code:

public class ServiceClient<TInput>
{
    private readonly IEnumerable<TInput> data;

    public ServiceClient(IEnumerable<TInput> dataInput)
    {
        this.data = dataInput;
    }

    public TResult Send<TResult>(Func<IEnumerable<TInput>, TResult> selector)
    {
        var selectedData = this.data.Select(selector); // How to do the selection here???

        // ...
    }
}

The class is called this way:

private static void Main(string[] args)
{
    var persons = new List<Person>
    {
        new Person { Id = 0, FamilyId = 0 },
        new Person { Id = 1, FamilyId = 0 },
        new Person { Id = 2, FamilyId = 1 }
    };

    var func = new Func<IEnumerable<Person>, Person>(Target);

    var client = new ServiceClient<Person>(persons);

    client.Send(func);
}

private static Person Target(IEnumerable<Person> enumerable)
{
    return enumerable.SingleOrDefault(p => p.Id == 0);
}

Upvotes: 0

Views: 264

Answers (2)

Yuriy A.
Yuriy A.

Reputation: 752

You need to change Send that way:

public TResult Send<TResult>(Func<IEnumerable<TInput>, TResult> selector)
{
     return selector(data);
}

Upvotes: 0

user2160375
user2160375

Reputation:

Replace:

var selectedData = this.data.Select(selector); 

with:

var selectedData = selector(this.data);

It should be enough. selector is delegate that acceps collection and returns single element, so you need invoke selector delegate with data argument.

If you would like to use Select like this.data.Select(..) your selector delegate should rather be like Func<TInput, TResult> - delegate that projects one element into another.

Upvotes: 4

Related Questions