Databinding multiple controls to a single LINQ query
I have a LIN开发者_JAVA百科Q query I wish to run and drop the result into a var or IQueryable. However, I'm binding the result to multiple (4 to 10) controls and only want the query to run once.
- When I just put the result into all the datasource values, the query runs for every control and the controls (comboboxes, for example), change selectedvalues to match each other whenever any of them is changed.
- When I databind the controls to the result.ToList() or something similar, that fixes the synchronization problem (i.e. they behave independently as they should), but the query still runs once for every control.
This was easycakes in ADO.NET days. How can I make the LINQ query run once and still databind to multiple controls?
Pseudocode:
var result = from c in dc.whatevers select c;
ddlItem1.DataSource = result;
ddlItem2.DataSource = result;
ddlItem3.DataSource = result;
Also:
var result = from c in dc.whatevers select c;
ddlItem1.DataSource = result.ToList();
ddlItem2.DataSource = result.ToList();
ddlItem3.DataSource = result.ToList();
Also:
List<whatever> result = (from c in dc.whatevers select c).ToList();
ddlItem1.DataSource = result;
ddlItem2.DataSource = result;
ddlItem3.DataSource = result;
The last option in your example is the easiest.
That will execute the query once, read it into memory, and use the in memory representation to bind to the controls
Calling ToList()
should force query execution a single time. Using the resulting list should NOT repeat the query but load the values from the in memory collection. Are you positive that the code you're running is both what you have above and actually running the queries four times?
Try this:
var result = from c in dc.whatevers select c;
List<whatevers> resultList = result.ToList(); // Query runs here
ddlItem1.DataSource = new List<whatevers>(resultList); // Copy of the list
ddlItem2.DataSource = new List<whatevers>(resultList); // Copy of the list
ddlItem3.DataSource = new List<whatevers>(resultList); // Copy of the list
精彩评论