使用C#泛型压缩代码

Mee*_*mfp 3 c# linq generics

我有以下2种方法可以使用泛型在一种方法中压缩.我试过的东西无法编译.有人能让我知道如何做到这一点?我需要检查表AgeLengths的2个不同字段是否至少有一个值.Str_table与AgeLengths有一对多的关系.

public static bool HasMeanWeight(int id)
{
    MyDataContext dc = new MyDataContext ();
    return  (from s in dc.Str_table 
             where s.SId == id 
             select s.AgeLengths
             .Where(a => a.MeanWeight != null ).Any() == true
            ).FirstOrDefault();
}

public static bool HasNumbersData(int id)
{
    MyDataContext dc = new MyDataContext ();
    return (from s in dc.Str_table 
            where s.sId == id 
            select s.AgeLengths
            .Where(a => a.Numbers  != null).Any() == true
           ).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢B.

Ada*_*rth 5

更新:道歉,我没有意识到这是linq to sql.丹尼斯的答案似乎就是标志.

尝试注入一个Func<T, TResult>注入不同的代码:

public static bool HasData(int id, Func<AgeLength, object> selector)
{
    MyDataContext dc = new MyDataContext ();
    return (from s in dc.Str_table 
            where s.sId == id 
            select s.AgeLengths
                .Where(a => selector(a) != null)
                .Any())
           .FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

并且这样打电话:

HasData(1, a => a.Numbers);
HasData(1, a => a.MeanWeight);
Run Code Online (Sandbox Code Playgroud)

如果NumbersMeanWeight属性在同一继承层次结构中,那么您可以object用更有用的东西替换,但在这个实例中object可以正常,因为您只是测试null.