我有一个自定义列表,如下所示。
class ActionToDo
{
public string Name {get;set;}
public DateTime dtDate {get;set;}
public string EventCode {get;set;}
public string EventDescription {get;set;}
}
我想做的是查找具有相同日期和日期的项目。相同的事件描述以及EventCode = "AQ"
的位置。我猜LINQ
是达到这个目标的最好方法吗?虽然使用LINQ
,但我不知道如何做到这一点。
在我的头脑中使用Sql
我认为它大致类似于下面的内容。
SELECT * FROM SomeTable
WHERE [EventDescription] = 'AQ'
GROUP BY [dtDate], [EventDescription]
答案 0 :(得分:2)
.Where(x=> x.EventDescription == "AQ")
.GroupBy(x => new { x.dtDate.Date, x.EventDescription})
答案 1 :(得分:2)
所以我们假设你有一个
List<ActionToDo> actionToDo = new List<ActionToDo>();
actionToDo.Where(i => i.EventDescription == "AQ" && i.EventCode="AQ")
.GroupBy(i => new { i.dtDate.Date, i.EventDescription });
答案 2 :(得分:1)
以下是使用符合您要求的查询语法表达的LINQ查询。此外,它还会对分组属性dtDate
和EventDescription
进行排序,然后按Name
对每个组的成员进行排序:
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;
}
}