将Linq分组并将列转换为行

时间:2018-07-02 13:56:08

标签: c# asp.net .net

我有一个列表,当前将返回类似这样的内容。 Att列可以是任何内容,因为用户可以随时输入Att和Value。

var attr_vals = (from mpav in _db.MemberProductAttributeValues
                             select mpav);

结果

Id        Att        Value
1         Color      Blue
1         Size       30
1         Special    Slim
3         Color      Blue
4         Size       30
2         Special    Slim
2         Random     Foo Foo

我正在寻找的转换将与此类似

已转换的结果

Id    Color    Size    Special    Random
1     Blue     30      Slim       null
2     null     null    null       Foo Foo
3     Blue     null    null       null
4     null     52      null       null

到目前为止,类看起来像这样。

public class MyMappProducts
{
    public int? id { get; set; }
    public Dictionary<string, string> Attributes { get; set; }

    string GetAttribute(string aName)
    {
        return Attributes[aName];
    }

    void setAttribute(string aName, string aValue)
    {
        Attributes[aName] = aValue;
    }
}

1 个答案:

答案 0 :(得分:3)

因此,鉴于您的属性列表可能会更改,因此将每个属性作为一个属性来创建一个类并不好,因为您必须事先了解所有属性,因此使用字典更加容易。
这是您想要做的一种方法(请注意,字典中不存在每行缺少的属性)

var list = new List<AttributeValue>
{
    new AttributeValue(1, "Color", "Blue"),
    new AttributeValue(1, "Size", "30"),
    new AttributeValue(1, "Special", "Slim"),
    new AttributeValue(3, "Color", "Blue"),
    new AttributeValue(4, "Size", "30"),
    new AttributeValue(2, "Special", "Slim"),
    new AttributeValue(2, "Random", "Foo Foo")
};

// First we groupby the id and then for each group (which is essentialy a row now)
// we'll create a new MyMappProducts containing the id and its attributes
var result = list.GroupBy(av => av.Id)
                    .Select(g => new MyMappProducts
                    {
                        id = g.Key,
                        Attributes = g.ToDictionary(av => av.Attribute, av => av.Value)
                    })
                    .ToList();

这将导致(精美打印):

[
  {
    "id": 1,
    "Attributes": {
      "Color": "Blue",
      "Size": "30",
      "Special": "Slim"
    }
  },
  {
    "id": 3,
    "Attributes": {
      "Color": "Blue"
    }
  },
  {
    "id": 4,
    "Attributes": {
      "Size": "30"
    }
  },
  {
    "id": 2,
    "Attributes": {
      "Special": "Slim",
      "Random": "Foo Foo"
    }
  }
]
相关问题