Passing some LINQ query into function argument?

I have the following code example in C # demonstrating how I would like to parse some LINQ query in a function 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 it some meaning, what I was thinking about achieving will be as follows:

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

It is hard to explain. I hope this example works well.

+6
source share
2 answers

Of course. 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 can 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 name it as follows:

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

But actually, in your simple example, this makes no sense, because it is exactly the same as directly using Where :

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

However, if your GetAll method performs some other actions, it makes sense to pass a predicate to this method.

+11
source

You can pass some kind of predicate to the method:

 var query = GetAll(x => x.ToString() == "lala"); // ... public IEnumerable<object> GetAll(Func<object, bool> predicate) { return AllElements.Where(predicate); } 
+1
source

Source: https://habr.com/ru/post/885395/


All Articles