2012-04-01 71 views
2

使用LINQ,我可以將表中的數據轉換爲下面直接顯示的格式嗎? LINQ可以執行這種格式化,還是應該循環執行格式化結果?如何使用以下格式將數據與LINQ格式化爲實體?

格式我試圖將數據導入:

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

數據如表:

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 

回答

2

實際的格式將是你的,但假設你有這些物品的集合稱爲list,您可以這樣做:

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) 

}; 

如果你真的在處理L2E,你可能不得不把它放到內存列表中去做這件事。

編輯:剛試了L2E,它似乎工作正常,因爲書面。在您的查詢中,不是list,而是context.TableName

以下是完整的代碼。輸出很sl but,但是很晚,我不認爲OP很擔心格式化太多:

 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();