Can we create a grouped list to normal list?

Here it is just an example. Suppose we have class Grouped (Items are gruoped by group name) as given below:

public class Grouped
  public int Id { get; set; }
  public string GroupName { get; set; }
  public List<Item> Items{ get; set; }

public class Item 
  public string ItemName { get; set; }

What i need to do is to make a list of Normal Class from the above Grouped Object using only linq c# but not using ForEach or ForLoop.

pubic class Normal
  public int Id { get; set;}
  public string GroupName { get; set;}
  public string ItemName { get; set;}

here is an example of list

Id Name Item
1 A X
1 A Y
2 B Y
3 C X
3 C Y
3 C Z

>Solution :

If you have a collection of Grouped (and you should, based on the desired output, otherwise there is no source for multiple Ids) you can use SelectMany to flatten a nested collection. Something along this lines:

IEnumerable<Grouped> grouped = ...;
var result = grouped
    .SelectMany(g => g.Items.Select(i => new Normal
        Id = g.Id,
        GroupName = g.GroupName,
        ItemName = i.ItemName

Leave a Reply