获取分组的泛型类的属性

时间:2017-07-04 21:38:39

标签: c# generics properties typeof

我有以下代码,它获取所有类型为string的属性,然后用于过滤源。

public IQueryable<T> FilterSource(IQueryable<T> source, string filter)
{
    var properties = typeof(T).GetProperties().Where(x => x.PropertyType == typeof(string)).Select(x => x.Name);
}

我的问题是源代码恰好是IGrouping,所以当我调用typeof(T).GetProperties()时,我只能访问分组键。而我需要在分组内的对象中获取属性。

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

如果您知道自己将传递IGrouping,则以下情况应该有效。但是,这种方式要求您传递密钥和分组对象的类型。

    public static void FilterSource<TKey,TElement>(IQueryable<IGrouping<TKey, TElement>> source, string filter)
    {
        //TElement is the type inside the grouping
        var properties = typeof(TElement).GetProperties().Where(x => x.PropertyType == typeof(string)) .Select(x => x.Name);
    }