我已经像数据表:从线性列表中选择项与子项列表
Group Item
1 1
1 2
2 3
2 4
我需要选择一个LINQ获得作为输出: IEnumerable<Group>
,其中
class Group
{
IEnumerable<Item> Items;
}
可能与一个表达?
谢谢!
UPD:LINQ到对象(我有数据表)
我已经像数据表:从线性列表中选择项与子项列表
Group Item
1 1
1 2
2 3
2 4
我需要选择一个LINQ获得作为输出: IEnumerable<Group>
,其中
class Group
{
IEnumerable<Item> Items;
}
可能与一个表达?
谢谢!
UPD:LINQ到对象(我有数据表)
既然你有一个DataTable
对象,不执行LINQ的接口,我建议你首先将它们转换成更多的东西“objecty”和比使用LINQ来提取数据。
东西线沿线的:
//setup
DataTable dt = new DataTable();
dt.Columns.Add("Group", typeof(int));
dt.Columns.Add("Item", typeof(int));
dt.Rows.Add(1, 1);
dt.Rows.Add(1, 2);
dt.Rows.Add(2, 3);
dt.Rows.Add(2, 4);
// transforms the datatable to an IEnumerable of an anonymous type
// that contains a Group and Item properties
var dataObjects = from row in dt.AsEnumerable()
select new { Group = row["Group"], Item = row["Item"] };
//after that it's just a group by application
var groups = from row in dataObjects
group row by row.Group into g
select new Group{ GroupID = g.Key
,Items = g.Select(i => i.Item)};
我假设Group
类有一个GroupID
属性组值。
这就是我需要的 –
// untested
var groups = from row in myTable
group row by row.Group into gr
select new Group { Items = gr.Select(g => g.Item) } ;
您需要LINQ到SQL或常规LINQ到对象吗? – SWeko
LINQ到对象(我有数据表) –