LINQ将数据分组到包含列表的对象列表中+选择特定的原始数据

时间:2016-05-19 17:33:50

标签: c# entity-framework linq grouping

我正在搜索此stackoverflow问题中给出的解决方案的扩展。 Using Linq to group a list of objects into a new grouped list of list of objects

如果我想将一堆PersonData分配到List中。如果我只想将emp字符串保留在ListData的标签内而不是Point Class中,我该怎么办?

return db.persondatas.Where.GroupBy(i => new { i.name, i.y })
                                    .Select(i => new Point
                                    {
                                        x = i.x
                                        emp = i.name
                                        y = i.Sum(s => s.y)
                                    })
                                    .GroupBy(i => i.emp)
                                    .Select(i => new ListData
                                    {
                                        label= i.Key,
                                        data= i.ToList()
                                    }).ToList();

public Class Point
{
  double x;
  double y;
}
public Class ListData
{
  List<Point> data;
  string label;
}
public Class PersonData
{
  string name;
  int x;
  int y;
}

1 个答案:

答案 0 :(得分:1)

以下是编写它的方法:

return db.persondatas
    //.Where(/* ... */)
    .GroupBy(x => x.name, (name, g) => new ListData
    {
        label = name,
        data = g.GroupBy(d => d.x, (x, data) => new Point
            {
                x = x,
                y = data.Sum(d => d.y)
            })
            .ToList()
    }).ToList();