2

Using LINQ can I get the data from the table into the format shown directly below? Can LINQ perform this type of formating or should I loop through the results to format?

Format I'm trying to get data into:

dau      gmu           population     year    
------   ----------    ----------    -------
1        2, 201        1680          2010
2        3, 4, 5, 14   14570         2010

DATA IN TABLE:

 id          dau         gmu         population         year species
----------- ----------- ----------- ------------------- ---- -------
1           1           2           1680                2010 E
2           1           201         1680                2010 E
3           2           3           14570               2010 E
4           2           4           14570               2010 E
5           2           5           14570               2010 E
6           2           14          14570               2010 E
KeelRisk
  • 749
  • 1
  • 9
  • 27

1 Answers1

2

The actual formatting will be up to you, but assuming that you have a collection of these items called list, you can do this:

var result = from x in list
             group x by new {x.dau, x.population, x.year} into p
             select new 
{
    dau = p.Key.dau,
    population = p.Key.population,
    year = p.Key.year,
    gmu = p.Select (x => x.gmu)

};

You may have to pull this into an in-memory list to do this, if you're actually dealing with L2E.

EDIT: Just tried it with L2E and it seems to work fine as written. Instead of list in your query, it will be something more like context.TableName.

Here's the full code. The output is very sloppy, but it's late, and I don't think the OP was worrying about the formatting so much:

        var result = from x in list.Stacko1
                     group x by new { x.dau, x.population, x.year } into p
                     select new
                     {
                         dau = p.Key.dau,
                         population = p.Key.population,
                         year = p.Key.year,
                         gmu = p.Select(x => x.gmu)

                     };

        result.ToList().ForEach(item=>
                                    {
                                        System.Console.Write("{0}\t\t", item.dau);

                                        item.gmu.ToList().ForEach(gmuElement=>
                                                                      {
                                                                          System.Console.Write("{0},", gmuElement);
                                                                      });


                                        System.Console.Write("\t\t");
                                        System.Console.Write("{0}\t\t", item.population);
                                        System.Console.WriteLine("{0}", item.year);
                                    });

        System.Console.ReadKey();
Robaticus
  • 22,857
  • 5
  • 54
  • 63