简体   繁体   English

将属性传递为参数以使用LINQ / C#创建过滤方法?

[英]Pass property as parameter to create a filtering method with LINQ/C#?

Suppose I have these classes: 假设我有这些课程:

private class Model
{
    public DateTime FirstDate { get; set; }
    public DateTime SecondDate { get; set; }
    public DateTime FinalDate { get; set; }
    public string Name { get; set; }
}
private class Mommasan : Bandana
{
    public DateTime RestDate { get; set; }
    public DateTime TurboDate { get; set; }
    public string Name { get; set; }
}

All dates need to be filtered up to 3 days. 所有日期最多需要过滤3天。 So how can I create a generic filtering method for the DateTime properties? 那么,如何为DateTime属性创建通用过滤方法? Using IQueryable ? 使用IQueryable吗? I was hoping it would end up something like this: 我希望它最终会变成这样:

(Obviously will not compile, but I'm guessing the idea) (显然不会编译,但是我猜这个主意)

void DoSpecificFilter<T>(ref IQueryable<T> query, DateTimeProperty property)
{
    DateTime today = today;
    query = query.Where(a => property <= today && today <= property.AddDays(3);
}

So if I need to filter Models who are on their final date, something like: 因此,如果我需要过滤最终日期的Models ,则类似:

DoSpecificFilter<Model>(ref alreadyFilteredQuery, a => a.FinalDate);

and Mommasans who are on rest: 和正在休息的Mommasans

DoSpecificFilter<Mommasan>(ref alreadyFilteredQuery, a => a.RestDate);

Is this kind of thing possible at all or am I having the entirely wrong idea? 这种事情有可能发生吗,还是我的想法完全错误? Thanks! 谢谢!

You could work with DateTime -Selectors. 您可以使用DateTime -Selectors。 For multiple DateTime fields you would have to chain them together. 对于多个DateTime字段,您必须将它们链接在一起。 It would probably be easier to write an extention method for this: 为此,编写扩展方法可能会更容易:

public static class ExtentionMethods
{
    public static IQueryable<T> DoSpecificFilter<T>(
        this IQueryable<T> query, 
        Expression<Func<T, DateTime>> dateSelector, 
        DateTime filterValue, 
        bool blnTopLimit)
    {
        return query.Where(a => (blnTopLimit && dateSelector.Compile()(a) < filterValue)
            || (!blnTopLimit && dateSelector.Compile()(a) > filterValue));
    }
 }

Then you could use it like this: 然后,您可以像这样使用它:

 var query = queryableCollection
     .DoSpecificFilter((a) => a.RestDate, DateTime.Today, false)
     .DoSpecificFilter((a) => a.TurboDate, DateTime.Today, true);

Why not write an extension method on DateTime, and not look at the class at all? 为什么不在DateTime上编写扩展方法,而根本不看类呢? Something like ... 就像是 ...

public static class Extensions
{
    public static IQueryable<T> DoSpecificFilter<T>(this DateTime value, IQueryable<T> query)
    {
        DateTime today = DateTime.Now;
        IQueryable<T> ret = query.Where(a => value <= today && today <= value.AddDays(3));
        return ret;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM