Return partial linq query from method - how to declare return type
I have a linq query written in method syntax. I need to create a very similar method with just some changes to the final Select.
Is it possible to return the partial Linq query from a method so I dont duplicate the code? The issue I have is finding the "Type" of the query to mark the method with.
If I use query.GetType(), it returns (cut down version) :
SubSonic.Linq.Structure.Query`1[<>f__AnonymousType18`6[advert,client]]
I tried to create a return type:
SubSonic.Linq.Structure.Query<advert, client> query = new SubSonic.Linq.Structure.Query<advert, client>();
However I receive the error:
Error 20 Using the generic type 'SubSonic.Linq.Structure.Query<T>' requires '1' type arguments
So I guess I am asking how to declare a return type that is a Subsonic Query containing an anonymous type containing a number of objects? (2 in my example)
Please excuse my simple example:
eg:
internal ????? GetQueryBody(string param1, string param2){
/* buld the linq query here */
}
internal List<Booking> GetSearchResultsOne(string param1, string param2){
var query = this.GetQueryBody(string param1, string param2);
var res = query.Select( db => new Booking { /*f开发者_开发问答ields */).ToList();
return res;
}
internal List<BookingData> GetSearchResultsTwo(string param1, string param2){
var query = this.GetQueryBody(string param1, string param2);
var res = query.Select( db => new BookingData { /*fields*/).ToList();
return res;
}
Thank you for your time,
Yohimbo
Use IEnumerable<T>
to return a query.
About the anonymous type: If a type is anonymous, how should another methode know about it? Read more here. To solve the problem, give your anonymous type a name by creating a class.
If you only want to return two types you could also return a tuple: Then T
is Tuple<advert,client>
. You can create a tuple by
var t = new Tuple<advert,client>(client, advert);
Answer 1: You can't do it because Booking and BookingData are different types so the expression trees are different.
Answer 2: Assuming you can find a common base class, there are two approaches to your question.
The 'type' of what a Linq Query acts on is actually an
Expression<TDelegate>
. You can construct Expression trees and store them and manipulate them, and then use them where needed.The 'argument' for your final Select() is actually an
Expression<Func<TSource, TResult>>
. You can use any function in that location as long as it conforms to that delegate.
In other words, you can store the entire pre-formed expression trees from the top, or you can store one tree and substitute the bit at the bottom. There isn't enough in your sample for me to write the code, and you still have to resolve that fatal flaw.
精彩评论