Home > Blockchain >  Ungroup list items using linq c#
Ungroup list items using linq c#

Time:02-11

I have a class which stores the menus data in below format.

public class MenuCondiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long[] CondimentIds { get; set; }
}

e.g.

GroupId Name CondimentIds
21 Veg Burger 100032,100033,100045,100056
22 Chiken Burger 100067,100040,100034

Now, I want the output data as below in the class by using linq.

public class Condiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentIds { get; set; }
}
GroupId Name CondimentIds
21 Veg Burger 100032
21 Veg Burger 100033
21 Veg Burger 100045
21 Veg Burger 100056
21 Chiken Burger 100067
22 Chiken Burger 100040
22 Chiken Burger 100034

Can someone assist here?

CodePudding user response:

You can use Linq and SelectMany() to flatten the inner array:

var menuCondiements = // get menucondiments

var result = menuCondiements
               .SelectMany(                // flatten the
                 m => m.CondimentIds       // inner array
                   .Select(
                     c => new Condiment    // project to 
                     {                     // new Condiment() 
                       GroupId = m.GroupId, 
                       Name = m.Name, 
                       CondimentId = c    // here condimentId is 'c'
                     }));

You should also rename your class and Id to singular rather than plural form since the class represents a single object:

public class Condiment
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentId { get; set; }
}

CodePudding user response:

You can try using classic foreach language construct. Below should give you idea.

var menuCondimentList = new System.Collections.Generic.List<MenuCondiments>
{
    new MenuCondiments {GroupId = 21, Name = "Veg Burger", CondimentIds = new long[] { 100032, 100033, 100045, 100056 } },
    new MenuCondiments {GroupId = 22, Name = "Chicken Burger", CondimentIds = new long[] { 100067, 100040, 100034 } }
};

var condimentList = new System.Collections.Generic.List<Condiments>();
// Using foreach
foreach ( var menuCondiment in menuCondimentList )
{
    foreach(var c in menuCondiment.CondimentIds )
    {
        condimentList.Add(new Condiments
        {
            GroupId = menuCondiment.GroupId,
            Name = menuCondiment.Name,
            CondimentId = c
        });
    }
}
  • Related