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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With