Reputation: 75
I have two DataTables , Items and its Groups. I have a linq query to get item Name and its Group Name by joining the 2 tables.
EnumerableRowCollection<DataRow> dvquery = (from item in Items.AsEnumerable()
join grp in groups.AsEnumerable()
on item.Field<byte>("Group_ID") equals grp.Field<byte>("ID")
into item_grp_join
from itemgrp in item_grp_join
select new
{
ItemName = (string)led.Field<string>("Name"),
GName = (string)itemgrp.Field<string>("Name"),
});
DataView dv = dvquery.AsDataView();
However I am getting compile time error as
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Data.EnumerableRowCollection'. An explicity conversion exists (are you missing a cast?)
How to solve this error? I can easily convert the query result into a list but I need to have a dataview only , so as I can give it as datasource to grid.
Any help appreciated. Thanks
Upvotes: 2
Views: 5588
Reputation: 66882
The problem is that your query returns an IEnumerable<T>
of an anonymous type and you can't simply cast that to a EnumerableRowCollection<DataRow>
I'm now sure which type of Grid you are using (e.g. from winforms? WPF? ASP? ASP MVC? etc), however I would expect that you should actually be able to pass it the IEnumerable output of the linq query if you wanted to - e.g.:
var query = (from item in Items.AsEnumerable()
join grp in groups.AsEnumerable()
on item.Field<byte>("Group_ID") equals grp.Field<byte>("ID")
into item_grp_join
from itemgrp in item_grp_join
select new
{
ItemName = (string)led.Field<string>("Name"),
GName = (string)itemgrp.Field<string>("Name"),
});
grid.DataSource = query; // or possible query.ToList() as you suggest in the question!
If you really need to use a DataView type object, then there are blog posts about how to create these, try:
Note that if you are expecting to use the grid for two-way binding (e.g. for writing changes back to the database), then this is unlikely to "just work" - as your IEnumerable projection isn't tied back to the datasource.
Upvotes: 4
Reputation: 94645
You are returning an list of anonymous
objects. It is better to create a DataTable from your query result.
var query = (from item in Items.AsEnumerable() .......
DataTable view = new DataTable();
view.Columns.Add("GroupName");
view.Columns.Add("ItemName");
foreach (var t in dvquery)
{
view.Rows.Add(t.GName, t.ItemName);
}
DataView dv = view.DefaultView;
Upvotes: 2