开发者

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

开发者 https://www.devze.com 2023-02-22 22:23 出处:网络
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.

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 exp开发者_开发技巧lain. 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消