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}
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…
thanks
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.)
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 anIEnumerable<T>instead – but theTis 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.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.
MyPointYour query would then be:
You’d then write your method as:
And call it as
SomeMethod(query);