两种LINQ方法执行相同的操作,但采用并返回不同的类型

private IQueryable<Type1>FilterBySomething(IQueryable<Type1> results)
{
    if (ThisField!= null)
    {
        results = results.Where(x => x.Thisfield == ThisField.Value);
    }
    return results;
}

private IQueryable<Type2>FilterBySomething(IQueryable<Type2> results)
{
    if (ThisField!= null)
    {
        results = results.Where(x => x.Thisfield == ThisField.Value);
    }
    return results;
}


问题是重复。我想要一个执行此操作的通用函数,但我不知道该怎么做

最佳答案

引入新界面:

interface IThisfieldSupported
{
    string Thisfield {get;set;}
}

设置限制:

private IQueryable<Type1> FilterBySomething<Type1>(IQueryable<Type1> results) where Type1 : class, IThisfieldSupported
{
    if (ThisField!= null)
    {
        results = results.Where(x => x.Thisfield == ThisField.Value);
    }
    return results;
}

用不同的类调用它,但是在这些类中实现IThisfieldSupported

class Data : IThisfieldSupported
{
    string Thisfield { get;set; }
    int Id { get;set; }
}
...
var data = new Data[10];
var result = FilterBySomething(data);

09-05 11:14