首页 > 解决方案 > Linq query of of two objects with nested array

问题描述

I have two objects pulled from from two separate JSON files. One is the source, the other is a reference to look up specific data from the source.

Source JSON:

 {
    "options": [
        {
            "id": 1,
            "product_id": 1,
            "size": "S",
            "color": "red"
        },
        {
            "id": 2,
            "product_id": 1,
            "size": "M",
            "color": "red"
        },
        {
            "id": 3,
            "product_id": 1,
            "size": "L",
            "color": "red"
        },
        {
            "id": 4,
            "product_id": 1,
            "size": "XL",
            "color": "red"
        },
        {
            "id": 5,
            "product_id": 1,
            "size": "S",
            "color": "blue"
        },
        {
            "id": 6,
            "product_id": 1,
            "size": "M",
            "color": "blue"
        },
        {
            "id": 7,
            "product_id": 1,
            "size": "L",
            "color": "blue"
        },
        {
            "id": 8,
            "product_id": 1,
            "size": "XL",
            "color": "blue"
        }
    ]
}

Lookup JSON:

{
    "product": {
        "styles": [
            {
                "color": "red",
                "options": [1,2,3,4]
            },
            {
                "color": "blue",
                "options": [5,6,7,8]
            }
        ]
    } 
}

Both are deserialized to C# models.

I need to get a list of distinct sizes across all options, so I'm querying like so:

var sizes = (from o in options
             from s in product.styles
             from ss in s.optionIds
             where ss == o.id
             select new Size
             {
                name = v.size,
                optionIds = // needs to be an array with all option ids 
             }
             ).ToList().GroupBy(ps => ps.name).Select(ps => ps.First()).ToList();

The from/where section works as expected and I get a list or distinct sizes, however, I also need to list all option ids in the new Size object...see comment in code.

The result array I'm expecting:

[
    {
        "name": "S",
        "optionIds": [1,5]
    },
    {
        "name": "M",
        "optionIds": [2,6]
    },
    {
        "name": "L",
        "optionIds": [3,7]
    },
    {
        "name": "XL",
        "optionIds": [4,8]
    }
]

标签: linq

解决方案


据我所知,您的“查找 JSON”不包含源中尚未找到的任何信息,因此用这些数据混淆水是没有意义的。

var sizes = options
    .GroupBy(o => o.size, o => o.id)
    .Select(g => new Size {name = g.Key, options = g.ToList()})
    .ToList()

推荐阅读