Linq查询按日期(月和年)过滤 [英] Linq query filter by date (Month and year)

查看:501
本文介绍了Linq查询按日期(月和年)过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class content
{
    public int Id { get; set; }
    public string name { get; set; }
    public DateTime date { get; set; }  
}


Id   name       date
1    content1   01/01/2013
2    content2   05/01/2013
3    content3   05/03/2013
4    content4   01/06/2013
5    content5   10/03/2012
6    content6   01/01/2012

我正在尝试如果查询通过'01/2013',则查询应返回内容ID 1,2. 有没有人知道如何查询上述情况?

I'm trying that if query passes '01/2013', query should return content id 1,2 . Is there anyone knows how to query above situation ?

推荐答案

看起来您应该可以做到:

Looks like you should be able to do:

// Type and property names changed to match .NET conventions
public IEnumerable<Content> GetContents(int year, int month)
{        
    return db.Contents // Or wherever you're getting data from
             .Where(c => c.Date.Year == year && c.Date.Month == month);
}

我将yearmonth分开作为单独的参数,因为这就是您描述的方式-如果您确实希望能够处理"01/2013"​​,则可能想要仅按'/'拆分,然后首先将每个片段解析为整数. (或者,将其解析为特定格式的日期,然后从中获取年份和月份.)

I've split out year and month as separate parameters, as that's how you described them - if you really want to be able to handle "01/2013" you would probably want to just split by '/' and parsing each of the pieces as an integer first. (Alternatively, parse it as a date in a specific format and then take the year and month from that.)

请注意,将每个值格式化为字符串是没有意义的,除非您小心,否则可能不正确. (例如,除非您明确指定区域性,否则,如果在模式中使用/,则会得到当前区域性的日期分隔符,这很可能不是您所期望的.)

Note that formatting each value as a string is pointless and potentially incorrect unless you're careful. (For example, unless you specify the culture explicitly, if you use / in the pattern you'll get the current culture's date separator, which may well not be what you expect.)

您实际上并没有在尝试匹配字符串模式-您正在尝试测试日期的年和月.上面的代码清楚地表达了这一点.字符串格式无关紧要.

You're not actually trying to match a string pattern - you're trying to test for the year and month of the date. That's what the code above expresses clearly. String formatting is an irrelevance.

这篇关于Linq查询按日期(月和年)过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆