Home > Enterprise >  Convert the format of a list of objects into another
Convert the format of a list of objects into another

Time:10-01

I have the following list of objects:

[
        {
            "example": "cat",
            "categories": ["group1", "group2", "group3"]
            
        },
        {
            "example": "dog",
            "categories": ["group1", "group3", "group4"]
            
        },
        {
            "example": "cow",
            "categories": ["group1"]
            
        }
]

I want to convert this to this format:

[
    {
        "category": "group1",
        "examples": ["cat", "dog", "cow"]

    },
    {
        "category": "group2",
        "examples": ["cat"]

    },
    {
        "category": "group3",
        "examples": ["cat", "dog"]

    },
    {
        "category": "group4",
        "examples": ["dog"]

    }
]

here are my classes:

public class Animals
{
    public string Example { get; set; }    
    public List<string> Categories { get; set; }
}

public class Groups
{
    public string Category { get; set; }    
    public List<string> Examples { get; set; }
}

How do I do that using linq?

CodePudding user response:

Use SelectMany to flatten and GroupBy to build groups again:

var query = animalList
    .SelectMany(a => a.Categories.Select(c => (Animal: a, Category: c)))
    .GroupBy(x => x.Category)
    .Select(g => new Groups{ Category = g.Key, Examples = g.Select(x => x.Animal) });

You can append Distinct to get unique animals and ToArray/ToList if you want a collection.

CodePudding user response:

Like Tim Schmelter's answer, just in query syntax, which is aesthetically more pleasing to my eye:

var result = (from a in animalList
              from c in a.Categories
              group a.Example by c into g
              select new Groups
              {
                  Category = g.Key,
                  Examples = g.ToList()
              }).ToList();

(NB: Since your classes represent a single animal and a single group, respectively, they should be named in singular.)

  • Related