views:

56

answers:

1

In Linq Dynamic Query, Scott Guthrie shows an example Linq query:

var query =
    db.Customers.
    Where("City == @0 and Orders.Count >= @1", "London", 10).
    OrderBy("CompanyName").
    Select("new( CompanyName as Name, Phone)");

Notice the projection new( CompanyName as Name, Phone). If I have a class like this:

public class CompanyContact {
    public string Name {get;set;}
    public string Phone {get;set;}
}

How could I essentially "cast" his result using the CompanyContact data type without doing a foreach on each record and dumping it in to a different data structure? To my knowledge the only .Select available is the Dymanic Query version which only takes a string and parameter list.

+4  A: 

A far as I can see from the article you cite, The dynamic query methods return IQueryable<> objects, which mean the normal Select() should be available.

var query = 
    db.Customers. 
    Where("City == @0 and Orders.Count >= @1", "London", 10). 
    OrderBy("CompanyName"). 
    Select( c => new CompanyContact {Name = c.CompanyName, c.Phone}); 

You may have to explicitly give the type for the Select

    Select<Customer>( c => new CompanyContact {Name = c.CompanyName, c.Phone}); 
James Curran
I may have to wrap the entire query minus the Select in a cast just to get the lambda enabled Select method.
Dr. Zim
The only thing the cast should do is enable the IntelliSense. If the object isn't that type before hand, casting won't be able to chagne it.
James Curran