将一些 LINQ 查询传递到函数的参数中?

发布于 2024-10-30 19:06:31 字数 433 浏览 0 评论 0原文

我有以下 C# 代码示例,演示了如何将一些 LINQ 查询解析为函数的参数。

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.

}

现在,为了赋予它一些意义,我想要实现的目标是:

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

这有点难以解释。我希望这个例子能做得很好。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

惯饮孤独 2024-11-06 19:06:31

当然。你会这样做:

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

你会这样调用它:

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

你甚至可以将它创建为扩展方法:

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

并这样调用它:

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

但实际上,在你的简单示例中,它没有任何意义,因为它完全是与直接使用 Where 相同:

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

但是,如果您的 GetAll 方法执行更多操作,则将谓词传递给该方法可能是有意义的。

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.

初吻给了烟 2024-11-06 19:06:31

您可以将某种谓词传递给该方法:

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

// ...

public IEnumerable<object> GetAll(Func<object, bool> predicate)
{
    return AllElements.Where(predicate);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文