I've datatable like:
Group Item
1 1
1 2
2 3
2 4
I need a linq select to get as output: IEnumerable<Group>
, where
class Group
{
IEnumerable<Item> Items;
}
Is that possible with one expression?
Thanks!
upd: LINQ-to-objects (I have datatable)
// untested
var groups = from row in myTable
group row by row.Group into gr
select new Group { Items = gr.Select(g => g.Item) } ;
Since you have a DataTable
object that does not implement the LINQ interfaces, I suggest you first cast them to something more "objecty" and than use LINQ to extract the data.
Something along the lines of:
//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)};
I assume that the Group
class has a GroupID
property for the group value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.