我有一个Status对象列表,其中包含int值和datetime,格式为
Tue Sep 30 21:22:02 +0000 2014
代码:
public class Status
{
public string created_at { get; set; }
public int value { get; set; }
}
现在,我想在图表上显示此信息,但仅限过去7天。
如何在C#中按日期对对象进行分组并设法获取此信息?我知道如何在SQL中做到这一点,但我不熟悉LINQ。
答案 0 :(得分:1)
我猜你需要将Status分组来计算或计算你班上的其他一些字段,这样你就可以在白天得到一些东西。
如果是,请给出以下示例
List<Status> statusList = new List<Status>();
statusList.Add(new Status() { Value = 12, CreatedAt = "Tue Sep 30 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 11, CreatedAt = "Tue Sep 30 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 10, CreatedAt = "Tue Sep 30 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 9, CreatedAt = "Sat Sep 27 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 8, CreatedAt = "Fri Sep 26 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 7, CreatedAt = "Thu Sep 25 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 6, CreatedAt = "Wed Sep 24 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 5, CreatedAt = "Tue Sep 23 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 4, CreatedAt = "Mon Sep 22 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 3, CreatedAt = "Sun Sep 21 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 2, CreatedAt = "Sat Sep 20 21:22:02 +0000 2014" });
statusList.Add(new Status() { Value = 1, CreatedAt = "Fri Sep 19 21:22:02 +0000 2014" });
var groups = from status in statusList
let date = DateTime.ParseExact(status.CreatedAt, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture)
group status by date into g
where g.Key.Date >= DateTime.Now - new TimeSpan(7, 0, 0, 0)
select g;
foreach (IGrouping<DateTime, Status> group in groups)
{
DateTime day = group.Key;
int countOfValues = group.Select(g => g.Value).Count();
Console.WriteLine("Day: {0}", day.ToString());
Console.WriteLine("countOfValues: {0}", countOfValues.ToString());
}
打印:
Day: 9/30/2014 4:22:02 PM
countOfValues: 3 //Three entries on Sep 30...
Day: 9/27/2014 4:22:02 PM
countOfValues: 1
Day: 9/26/2014 4:22:02 PM
countOfValues: 1
Day: 9/25/2014 4:22:02 PM
countOfValues: 1
Day: 9/24/2014 4:22:02 PM
countOfValues: 1
答案 1 :(得分:0)
尝试添加以下内容,然后您的SP / SQL查询将在7天内仅返回记录。
datediff(day, created_at, getdate()) < 7
答案 2 :(得分:0)
如果您使用的是int(它非常糟糕,但确定..)那么首先您必须将int转换为datetime:在Google int to datetime
上搜索。
实施TimeSpan
的第二步,并为Datetime
和TimeSpan
使用覆盖运算符。
public bool LaterThan7Days(int valueFromClass)
{
DateTime myTime = //here convert valueFromClass to Datetime, search in google please
TimeSpan t = new TimeSpan(7,0 , 0, 0); //days, hours ,mins, seconds
DateTime timeToCompare = myTime + t;
return timeToCompare > DateTime.Now;
}
,查询应如下所示:
var query = from Status in yourContext
where LaterThan7Days(Status.value)
select Status;
query.ToList().Foreach(p=> Console.WriteLine(p.created_at));