Dennis G
Dennis G

Reputation: 21778

Linq group by with subselect of grouped items

I'm trying to create/fill an object MyObject using LINQ:

public class MyObject
{
    public string Title { get; set; }
    public List<Item> Items { get; set; }
}

public class Item
{
    public string Title { get; set; }
    public string Color { get; set; }
    public int Value { get; set; }
}

And I have a DataTable with the following content:

Title        Color        Value
-----        -----        -----
Something    Green        14
Title 2      Red          7
Title 4      Green        5
More         Green        12
Title 8      Red          6

How would I go about and create MyObject grouped by color? I tried with LINQ and I'm fine with grouping, but I don't know how to get the Items filled:

var groupedObjects = from row in dataTable.AsEnumerable()
                     group row by row.Field<string>("Color")
                     into grp
                     select new MyObject
                     {
                       Name = grp.Key
                       //,Items = this is where I don't know how to continue.
                       //Subselect to get all items where grp.Key == row.Field<string>("Color")?
                     };

My end result should be something like this (JSON, I guess this would be List<MyObject>):

{
  "Title" : "Green",
  "Items": [
      {
        "Title" : "Something",
        "Color" : "Green",
        "Value" : 14
      },
      {
        "Title" : "Title 4",
        "Color" : "Green",
        "Value" : 5
      }
    ],
  "Title" : "Red",
  "Items": [
      {
        "Title" : "Title 2",
        "Color" : "Red",
        "Value" : 7
      },
      {
        "Title" : "Title 8",
        "Color" : "Red",
        "Value" : 6
      }
    ]
}

Upvotes: 0

Views: 140

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You already have the groups so you just need to project items in the group and transform them into a Items, you don't need an additional filtering:

var groupedObjects = from row in dataTable.AsEnumerable()
                 group row by row.Field<string>("Color")
                 into grp
                 select new MyObject
                 {
                    Name = grp.Key,
                    Items = grp.Select(x => new Item 
                                            { 
                                               Title = x.Field<string>("Title"),
                                               Color = x.Field<string>("Color"), 
                                               Value = x.Field<int>("Value")
                                            }).ToList()
                 };

Upvotes: 1

Related Questions