0

I am searching for an extension to the solution given in this stackoverflow question. Using Linq to group a list of objects into a new grouped list of list of objects

If I wanted to devide a bunch of PersonData into a List. How should I proceed if I only want to keep the emp string inside the label of ListData and not in the 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;
}
Community
  • 1
  • 1
Hinnom
  • 25
  • 5

1 Answers1

1

Here is how you can write it :

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();
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44
  • I wanted the sum of y values on the same x value. So I think I should do g.GroupBy(s=>s.x).select(data => new point { x = data.Key, y = data.Sum(f=>f.y) }).ToList() Is this right? if so, change your code sample please and I'll accept it. – Hinnom May 19 '16 at 18:25
  • @Hinnom Correct. You can also write both `GroupBy`+`Select` in one single `GroupBy`. – Xiaoy312 May 19 '16 at 18:40