linq 将对象列表的格式转换为其他格式

fhg3lkii  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(146)

我有以下对象列表:

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

我想将其转换为以下格式:

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

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

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

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

    }
]

下面是我的课程:

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; }
}

我如何使用linq实现这一点?

eivgtgni

eivgtgni1#

使用SelectMany展平,使用GroupBy再次构建组:

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) });

您可以附加Distinct以获得独特的动物,如果您想要一个集合,则可以附加ToArray/ToList

9gm1akwq

9gm1akwq2#

就像Tim Schmelter的答案一样,只是在查询语法中,这在美学上更令我满意:

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:由于您的类分别表示一种动物和一个组,因此它们应该以单数形式命名。)

相关问题