Selecting columns from a LINQ query
I want to be able to select the columns that are displayed in my DataGridView. I.e., I have a linq query that returns an IEnumerable but I don't want to display all the properties of Policy - I want to allow the user to choose what to display. So I thought something like this might work to create a "narrower" object with only the columns I want.
IEnumerable<Policy> policies = repository.GetPolicies();
var results = from p in policies select new {
if (userPicked("PropertyOne")) PropertyOne = p.PropertyOne,
if (userPicked("PropertyTwo")) PropertyTwo = p.PropertyTwo,
...
};
dataGridView1.DataSource = results;
Is there an elegant way to do this?
Part 2: Why does this work:
IEnumerable<Policy> policies = repository.GetPolicies();
dataGridView1.D开发者_开发百科ataSource = policies;
but this doesn't:
IEnumerable<Policy> policies = repository.GetPolicies();
var results = from p in policies select p;
dataGridView1.DataSource = results;
In the second case nothing is displayed in the grid.
Use Dynamic Linq if you need to select fields dynamically. It contains a Select
extension method that accepts a string of fields, so you can decide which fields to select at runtime:
public static IQueryable Select(this IQueryable source,
string selector, params object[] values);
Example of usage:
var products = db.Products
.Where(condition)
.OrderBy("Name")
.Select(" new (ItemId,Name,Model,onsale)");
Part 2: Your grid is expecting a bindable interface such as IList
, but the second code example returns an IQueryable
. You can convert it to an IList
by calling ToList()
.
var results = (from p in policies select p).ToList();
精彩评论