星期二, 7月 08, 2008

linq如何group兩欄位

先看一下基本的用法..

//這是資料
var li = new[] {
new { title = "q1", content = "c123456" },
new { title = "q1", content = "c524136" },
new { title = "q1", content = "c123456" },
new { title = "q2", content = "c12dfa" },
new { title = "q2", content = "c12sdfadsf" },
new { title = "q3", content = "cdfs3sdfd" },
new { title = "q3", content = "cdfad56" },
new { title = "q4", content = "c1fsdaf456" },
new { title = "q4", content = "c12afds6" },
new { title = "q4", content = "c1dfadsf456" }
};

//把資料group起來
var aaaa = from a in li
group a by a.title into g
select g;

//列出資料
foreach (var a in aaaa)
{
Response.Write("主題:" + a.Key + "<br />");
foreach (var b in a)
{
Response.Write("-----" + b.content + "<br />");
}
Response.Write("<br />");
}

這是基本的用法..那現在問題是..如果我們group要用兩個欄位呢?..要如何使用..直接看例子..

//這是資料
var li = new[] {
new { title = "q1", tag = "aa", content = "c123456" },
new { title = "q1", tag = "aa", content = "c524136" },
new { title = "q1", tag = "ab", content = "c123456" },
new { title = "q2", tag = "au", content = "c12dfa" },
new { title = "q2", tag = "au", content = "c12sdfadsf" },
new { title = "q3", tag = "aa", content = "cdfs3sdfd" },
new { title = "q3", tag = "aa", content = "cdfad56" },
new { title = "q4", tag = "aa", content = "c1fsdaf456" },
new { title = "q4", tag = "aa", content = "c12afds6" },
new { title = "q4", tag = "an", content = "c1dfadsf456" }
};

//把資料group起來
var aaaa = from a in li
group a by new { a.tag, a.title } into g //<-----------------重點在這
select g;

//列出資料
foreach (var a in aaaa)
{
Response.Write("主題:" + a.Key.title + " , " + a.Key.tag + "<br />");
foreach (var b in a)
{
Response.Write("-----" + b.content + "<br />");
}
Response.Write("<br />");
}

完成..Tongue..

參考:

沒有留言: