拆分集合linq实体框架

时间:2016-08-26 12:12:11

标签: c# entity-framework linq

我有一个PropertyValues实体,它重复出现产品属性:

public enum Property { Color = 1, Brand, Size }

public class PropertyValue
{
    public int PropertyValueId { get; set; }
    public Property PropertyId { get; set; }
    public string Value { get; set; }

    public ICollection<Product> Products { get; set; }

    public PropertyValue()
    {
        Products = new HashSet<Product>();
    }
}

因为我们已经结束了产品属性,我创建了一个保存属性的枚举属性。 我正在尝试实现以下结果 - 根据属性拆分集合。其中值是另一个词典

        Dictionary<Property, Dictionary<int, string>> dict = new Dictionary<Property, Dictionary<int, string>>()
        {
            new KeyValuePair<Property, Dictionary<int, string>>()
            {
                {
                    Property.Color,
                    new KeyValuePair<int, string>()
                    {
                        { 5, "white" }, // ProperyValueId, Value
                        { 6, "green"}
                    }
                }
            }
        }

我被看作GroupBy和SelectMany,但没找到办法。 现在我有以下内容:

            var query = await db.PropertyValues
            .OrderBy(prop => prop.PropertyId)
            .Where(prop => prop.PropertyId == Property.Brand)
            .ToDictionaryAsync(prop => prop.PropertyValueId, prop => prop.Value);

        Dictionary<Property, Dictionary<int, string>> properties = new Dictionary<Property, Dictionary<int, string>>();
        properties.Add(Property.Brand, query);

应该返回一个json。但首先需要获得序列。 Json应该看起来像:

[{
{"colors": [{"5", "Black"}, {"7", "White"}]}, 
{"brands": [{"78", "Q&Q"}, {"24", "Adidas"}]},
}]

1 个答案:

答案 0 :(得分:2)

第一个GroupBy将PropertyValues的列表拆分为PropertyId,然后将此分组转换为以PropertyId为键的字典。

我们字典的每条记录的值都是通过创建一个新词典来构成的,其中键为PropertyValueId,值为Value

PropertyValues.GroupBy( k => k.PropertyId )
    .ToDictionary( k => k.First().Value, 
          k => k.ToDictionary( p => p.PropertyValueId, p => p.Value ) );

现在数据按您的意愿构建。