Problem with grid when trying to use groupby in LINQ
When trying to use GROUPBY I get an error saying a field 'date1' is not found on selected resource.
var query = (from a in db.Dates
from b in db.Facts
where a.Count_Key == b.Date_key
select new{
a.Date1,
a.Month,
开发者_运维知识库 b.Fact_key
});
var query2 = query.GroupBy(x => x.Month );
Grid1.DataSource = query2;
Grid1.DataBind();
So, when I try to bind with query it works perfectly, but query2 yields the error
field date1 not found on selected datasource.
How can I fix this?
The group by returns columns with different names than the original select.
You can do the following to see it "for educational purpose".
create a new Grid2 and use it with automatic columnmapping. Bind Query2 to this Grid2 and you will see the result.
Because you grouped by month, now you have only month field as a key, and collection of grouped items. If you want more fields on data source you need to use aggregate function on date1 field.
For example like this:
var query2 = (from q in query
group q by q.Month into g
select new
{
Month = g.Key,
Date = g.Select(gg=>gg.Date1).Max //or you can use first here etc.
}).ToList()
hope this helps
精彩评论