我已經像數據表:從線性列表中選擇項與子項列表
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到對象(我有數據表) –