Limit Linq result columns for GridView

2019-08-14 04:57发布

问题:

I have this static method in my business layer for returning Dinners

public static System.Collections.Generic.List<Dinner> GetDinners()
{
    using (DataClassesDataContext h = new DataClassesDataContext())
    {
        var query = (from dins in h.Dinners
                     where dins.Title == "New York"
                     select dins);
        return query.ToList();
    }
}

I use this to populate a grid in my aspx page.

protected void Page_Load(object sender, EventArgs e)
{
    GridView1.DataSource = BusinessLayer.GetDinners();
    GridView1.DataBind();
}

I want to limit the returned columns at the business layer level. Which I can do in Linq like this.

        var query = (from dins in h.Dinners
                     where dins.Title == "New York"
                     select new { dins.Title, dins.DinnerID });

But then I get an anonymous type error, which makes sense, but how do I get around this correctly?

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to   
'System.Collections.Generic.List<Dinner>

回答1:

You can not return anonymous types from method unless the return type is dynamic. Otherwise you need to create a separate class for the result and project that in your select statement.

Either change the signature to as follows:

public static System.Collections.Generic.List<dynamic> GetDinners()
{

And then return your query like so:

return query.ToList().Cast<dynamic>().ToList();

Or create a class and return list of that instead of using Anonymous type.