我如何通过LINQ查询的方法? [英] How do I pass a Linq query to a method?

查看:109
本文介绍了我如何通过LINQ查询的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个LINQ查询的方法,我怎么指定的参数类型?

I'd like to pass a Linq query to a method, how do I specify the argument type?

我的链接查询看是这样的:

My link query look something like:

var query =
    from p in pointList
    where p.X < 100
    select new {X = p.X, Y = p.Y}

显然我是新来的LINQ,并可能会摆脱接收方法,最终,当我转换了我的code中的休息,但似乎喜欢的事,我应该知道...

clearly I'm new to Linq, and will probably get rid of the receiving method eventually when I convert the rest of my code, but it seems like something I should know...

感谢

推荐答案

您需要的将是使用普通类型的投影,或者让你传递给通用和方法(这将意味着你可以'T做尽可能多的用它)。究竟是什么你想怎么办?如果你需要从方法使用X和Y值,你一定会需要创建一个普通型。 (有避免它可怕的哈克的方式,但他们不是一个好主意。)

You'll need to either use a normal type for the projection, or make the method you're passing it to generic as well (which will mean you can't do as much with it). What exactly are you trying to do? If you need to use the X and Y values from the method, you'll definitely need to create a normal type. (There are horribly hacky ways of avoiding it, but they're not a good idea.)

注:一些其他的答案正在谈论的IQueryable&LT; T&GT; ,但没有迹象表明,你正在使用什么比LINQ到对象,在这种情况下, 会是一个的IEnumerable&LT; T&GT; 代替 - 但是目前的 T 是一个匿名类型。这就是你需要的工作,如果你想在每个项目中使用的各个值的位。如果你的没有的使用L​​INQ to对象,请澄清的问题,我会编辑这个答案。

Note: some other answers are currently talking about IQueryable<T>, but there's no indication that you're using anything more than LINQ to Objects, in which case it'll be an IEnumerable<T> instead - but the T is currently an anonymous type. That's the bit you'll need to work on if you want to use the individual values within each item. If you're not using LINQ to Objects, please clarify the question and I'll edit this answer.

例如,把你的当前查询(这是稍微坏了,因为你不能同时采用两种投影初始化两次同名的X)。你会创建一个新的类型,例如 MyPoint

For example, taking your current query (which is slightly broken, as you can't use two projection initializers twice with the same name X). You'd create a new type, e.g. MyPoint

public sealed class MyPoint
{
    private readonly int x;
    private readonly int y;
    public int X { get { return x; } }
    public int Y { get { return y; } }

    public MyPoint(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

您的查询将被:

var query =
    from p in pointList
    where p.X < 100
    select new MyPoint(p.X, p.Y);

您会然后再编写方法:

public void SomeMethod(IEnumerable<MyPoint> points)
{
    ...
}

和称呼其为的someMethod(查询);

这篇关于我如何通过LINQ查询的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆