techie net20
techie net20

Reputation: 53

Linq query to return object list with multiple child arrays

Incoming list

    var list = new List<Franchise>()
    {
     new Franchise()
     {Id = 10, Name = "Franchise1", Code= "DD1", IsDomestic= 1, ParentCompanyId=1, GroupId=100 },        
     new Franchise()
     {Id = 10, Name = "Franchise1", Code= "DD1", IsDomestic= 1, ParentCompanyId=2, GroupId=100 },
     new Franchise()
     {Id = 10, Name = "Franchise1", Code= "DD1", IsDomestic= 1, ParentCompanyId=3, GroupId=200 },
     new Franchise()
     {Id = 15, Name = "Franchise5", Code= "FD1", IsDomestic= 0, ParentCompanyId=4, GroupId=300 },
     new Franchise()
     {Id = 15, Name = "Franchise5", Code= "FD1", IsDomestic= 0, ParentCompanyId=3, GroupId=300 },
     new Franchise()
     {Id = 15, Name = "Franchise5", Code= "FD1", IsDomestic= 0, ParentCompanyId=2, GroupId=400 },
   };

I want this to be transformed to list of the class below using LINQ

    public class FranchiseNew
    {
        public int Id { get; set; }
        public string Name{ get; set; }
        public int[] CategoryIds { get; set; }
        public int[] DivisionIds { get; set; }
        public int IsDomestic{ get; set; }
     }

output - one row per franchise with ParentCompanyIds and GroupIds in arrays

    var list = new List<Franchise>()
    {
       new Franchise()
       {Id = 10, Name = "Franchise1", Code= "DD1", IsDomestic= 1, ParentCompanyIds=[1, 2, 3], GroupIds = [100, 200 ]},        
       new Franchise()
       {Id = 15, Name = "Franchise2", Code= "FD1", IsDomestic= 0, ParentCompanyIds=[4, 3, 2], GroupIds = [300, 400] }
    };

What is the efficient LINQ query to achieve this? Thanks in advance.

Upvotes: 0

Views: 972

Answers (1)

sri harsha
sri harsha

Reputation: 680

You can try like below:

var collectionGroup = list.GroupBy(x => new { x.Name, x.Id, x.Code, x.IsDomestic }).ToList();
var result = collectionGroup.Select(x => new FranchiseNew
        {
            Id = x.Key.Id,
            Name = x.Key.Name,
            Code = x.Key.Code,
            IsDomestic = x.Key.IsDomestic,
            CategoryIds = x.GroupBy(s => s.ParentCompanyId).Select(y => y.Key).ToArray(),
            DivisionIds = x.GroupBy(s => s.GroupId).Select(y => y.Key).ToArray()
        }).ToList();

And in you're FranchiseNew model, add Code field.

Upvotes: 1

Related Questions