下面是一個LINQ查詢使用,以滿足您的要求查詢語法表示。此外,它也由Name
排序分組屬性dtDate
和EventDescription
,然後將每個組的成員:
var actions = new List<ActionToDo>();
// populate 'actions'
var results =
from a in actions
where a.EventCode == "AQ"
orderby a.dtDate, a.EventDescription, a.Name
group a by new { a.dtDate, a.EventDescription };
爲了證明這個查詢,我創建了一個程序與隨機順序一些樣品ActionToDo
數據。請看下面的程序格式化輸出,然後是程序本身。
演示程序輸出
[2014-02-12] [Desc.AQ.12]
AQ.12a
AQ.12b
[2014-02-13] [Desc.AQ.13]
AQ.13a
AQ.13b
AQ.13c
[2014-02-14] [Desc.AQ.14]
AQ.14a
AQ.14b
示範項目
using System;
using System.Collections.Generic;
using System.Linq;
class GroupByDemo
{
static public void Main(string[] args)
{
var actions = new List<ActionToDo>()
{
new ActionToDo("AQ.14b", "2014-02-14", "AQ", "Desc.AQ.14"),
new ActionToDo("AQ.12a", "2014-02-12", "AQ", "Desc.AQ.12"),
new ActionToDo("AQ.13b", "2014-02-13", "AQ", "Desc.AQ.13"),
new ActionToDo("XX.01", "2014-02-01", "XX", "Desc.XX.01"),
new ActionToDo("AQ.14a", "2014-02-14", "AQ", "Desc.AQ.14"),
new ActionToDo("AQ.12b", "2014-02-12", "AQ", "Desc.AQ.12"),
new ActionToDo("AQ.13a", "2014-02-13", "AQ", "Desc.AQ.13"),
new ActionToDo("XX.02", "2014-02-02", "XX", "Desc.XX.02"),
new ActionToDo("AQ.13c", "2014-02-13", "AQ", "Desc.AQ.13"),
new ActionToDo("XX.03", "2014-02-03", "XX", "Desc.XX.03")
};
var results =
from a in actions
where a.EventCode == "AQ"
orderby a.dtDate, a.EventDescription, a.Name
group a by new { a.dtDate, a.EventDescription };
foreach (var group in results)
{
Console.WriteLine("[{0}] [{1}]",
group.Key.dtDate.ToString("yyyy-MM-dd"),
group.Key.EventDescription);
foreach (var action in group)
{
Console.WriteLine(" {0}", action.Name);
}
}
}
}
class ActionToDo
{
public string Name {get;set;}
public DateTime dtDate {get;set;}
public string EventCode {get;set;}
public string EventDescription {get;set;}
public ActionToDo(
string name,
string dtDateString,
string eventCode,
string eventDescription)
{
this.Name = name;
this.dtDate = DateTime.Parse(dtDateString);
this.EventCode = eventCode;
this.EventDescription = eventDescription;
}
}