Sasha Reminnyi
Sasha Reminnyi

Reputation: 3532

Select items from linear list into list with subitems

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)

Upvotes: 0

Views: 248

Answers (2)

SWeko
SWeko

Reputation: 30912

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.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273581

// untested
var groups = from row in myTable
   group row by row.Group into gr
   select new Group { Items = gr.Select(g => g.Item)  } ;

Upvotes: 2

Related Questions