Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }))
    .ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading