将名称从参数传递给Linq查询

时间:2017-08-18 09:25:02

标签: c# linq

我可以这样做:

public int CountSpesific(string queryString, string namaKategori, string namaLaporan)
{
    var results = GetSearchResults(queryString); //will result in list
    var count = results.Where(o => o.KlasifikasiLaporan == namaLaporan 
                                  && o.[namaKategori] == true).Count();

    return count;
}

我想根据参数

更改[namaKategori]

1 个答案:

答案 0 :(得分:0)

您可以使用反射来获取属性信息,然后获取值。在下面的代码中,YourType是lambda表达式中o的类型。

query = query.OrderBy(x => prop.GetValue(x, null));

public int CountSpesific(string queryString, string namaKategori, string namaLaporan)
{
    System.Reflection.PropertyInfo prop = typeof(YourType).GetProperty(namaKategori);

    var results = GetSearchResults(queryString); //will result in list
    var count = results.Where(o => o.KlasifikasiLaporan == namaLaporan 
                           && (bool)prop.GetValue(o) == true).Count();

    return count;
}