Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing some of a LINQ query into an argument of a function?

Tags:

c#

linq

I have the following code sample in C# demonstrating how I would like to parse some of a LINQ query into a function's argument.

public List<object> AllElements;

public object GetAll<T>(SomeLINQQuery) {

    //get some elements from AllElements where the argument is added to the query, as shown below.

}

And now, to give this some meaning, what I was thinking of accomplishing would be this:

public void test() {
    GetAll<object>(where object.ToString() == "lala");
}

It's kind of hard to explain. I hope this example does it well.

like image 358
Mathias Lykkegaard Lorenzen Avatar asked Apr 07 '11 09:04

Mathias Lykkegaard Lorenzen


2 Answers

Sure. You would do it like this:

public List<T> GetAll<T>(List<T> list, Func<T, bool> where)
{
    return list.Where(where).ToList();
}

You would call it like this:

var result = GetAll(AllElements, o => o.ToString() == "lala");

You could even create it as an extension method:

public static List<T> GetAll<T>(this List<T> list, Func<T, bool> where)
{
    return list.Where(where).ToList();
}

and call it like this:

var result = AllElements.GetAll(o => o.ToString() == "lala");

But really, in your simple example, it doesn't make any sense, because it is exactly the same as using Where directly:

var result = AllElements.Where(o => o.ToString() == "lala").ToList();

However, if your GetAll method does some more stuff, it could make sense to pass the predicate to that method.

like image 103
Daniel Hilgarth Avatar answered Nov 18 '22 04:11

Daniel Hilgarth


You could pass some sort of predicate to the method:

var query = GetAll(x => x.ToString() == "lala");

// ...

public IEnumerable<object> GetAll(Func<object, bool> predicate)
{
    return AllElements.Where(predicate);
}
like image 33
LukeH Avatar answered Nov 18 '22 04:11

LukeH