开发者

Linq GroupBy Projection with Multiple Groups

I have a table in a DB that stores a Data Value and a two tiered label.

Data
{
     int ID,
     string Label,
     string Section,
     doub开发者_运维知识库le Value
}

An example entry, to illustrate my problem:

{"Sport", "", 12}
{"Sport", "Baseball", 33}
{"Sport", "Football", 44}

{"Food", "", 34}
{"Food", "Pizza", 56}
{"Food", "Donuts", 19}

I'd like to be able to print out the values like so:

Sport    | 12
Baseball | 33
Football | 44

Food     | 34
Pizza    | 56
Donuts   | 19

This is the code I have that accomplishes like 50% of what I want:

var first = (from d in db.Data
             where d.ID= PARAM
             select d);

var row = first.GroupBy(x => x.Label);

         foreach (var k in row)
         {
             Console.Write(k.Key + "\t|");

             foreach (var j in k)
             {
                 Console.Write(j.Data);
             }

             Console.Write("\n");
         }

But this just prints out:

Sport    | 12
Sport    | 33
Sport    | 44

Food     | 34
Food     | 56
Food     | 19

I understand why, I just don't know how to access the .Section attribute from the k.key part.

How can I use linq to achieve my desired output?

I got it to work:

var row = first.GroupBy(x => new {x.Label, x.Section});

         foreach (var k in row)
         {
             Console.Write(k.Key.Section == null || k.Key.Section == "" ? k.Key.Label : k.Key.Section);  
         ...
         }

New question:

How do I detect the edge of "Sport"/"Food." I want to insert a divider (------------);


 foreach (var group in groups)
 {
     foreach (var item in group)
     {
         string label = !string.IsNullOrEmpty(item.Section)
                      ? item.Section
                      : item.Label;

         Console.WriteLine("{0,-8} | {1}", label, item.Data);
     }

     Console.WriteLine("-------------");
 }

should print

Sport    | 12
Baseball | 33
Football | 44
-------------
Food     | 34
Pizza    | 56
Donuts   | 19
-------------
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜