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 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.
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;
}
}
Your query would then be:
var query =
from p in pointList
where p.X < 100
select new MyPoint(p.X, p.Y);
You'd then write your method as:
public void SomeMethod(IEnumerable<MyPoint> points)
{
...
}
And call it as SomeMethod(query);
I think what you are looking for is the Expression class. For instance,
public void DoSomething()
{
User user = GetUser(x => x.ID == 12);
}
IQueryable<User> UserCollection;
public User GetUser(Expression<Func<User,bool>> expression)
{
return UserCollection.expression;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With