如何使用LINQ C#从System.Collections.IEnumerable获取Properities列表

时间:2016-03-29 11:12:03

标签: c# wpf linq datagrid itemssource

我需要使用WPF中的DataGrid控件的System.Collections.IEnumerable来获取模型类属性列表。

DataGrid Control具有属性public IEnumerable ItemsSource { get; set; }

考虑为ItemsSource分配以下列表:List<Person> EmpList

void Main()
{
    List<Person> EmpList = new List<Person>()
    {
        new Person() {ID = 101, Name = "Peter", Gender = "Male", Role = "Manager"},
        new Person() {ID = 102, Name = "Emma Watson", Gender = "Female", Role = "Assistant"},
        new Person() {ID = 103, Name = "Kaliya", Gender = "Manager", Role = "Assistant"},
    };
}

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string Role { get; set; }
}

我需要使用public IEnumerable ItemsSource { get; set; }

获取属性名称

我使用List<Person> EmpList

尝试了
EmpList.GetType()
    .GetInterfaces()
    .Where(t => t.IsGenericType == true
        && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
    .Select(t => t.GetGenericArguments()[0])
    .FirstOrDefault().GetProperties()
    .Select(x => x.Name).ToList();

上述查询的输出是

enter image description here

像这样我需要使用 DataGrid ItemsSource

获取模型属性

我在Datagrid控件类中使用this.ItemsSource尝试了它,但我无法获取List。但ItemsSource充满了3个与上述集合相同的集合。

this.ItemsSource.GetType()
    .GetInterfaces()
    .Where(t => t.IsGenericType == true
        && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
    .Select(t => t.GetGenericArguments()[0])
    .FirstOrDefault().GetProperties()
    .Select(x => x.Name).ToList().Dump();

我需要使用this.ItemsSource提供与上面相同的输出。请帮助我如何实现这个???

我尝试了@bhuvin方法 - 反思,但我得到了空结果

屏幕截图1 :使用List正确加载ItemsSource enter image description here

屏幕截图2 :我得到了一组空的结果 enter image description here

逐步拍摄类型信息和属性信息快照

类型信息:

enter image description here

物业资讯:

enter image description here

2 个答案:

答案 0 :(得分:0)

    using System.Reflection;  // reflection namespace

    // get all public static properties of ObjList's type
    PropertyInfo[] propertyInfos;
    //objList might be any type of Collection.
    propertyInfos = objList.GetType().GetProperties(BindingFlags.Public |
                                                  BindingFlags.Static);
    // sort properties by name
    Array.Sort(propertyInfos,
            delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
            { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

    // write property names
    foreach (PropertyInfo propertyInfo in propertyInfos)
    {
      Console.WriteLine(propertyInfo.Name);
    }

答案 1 :(得分:0)

假设PersonsGrid是Datagrid控件的名称,以下代码应返回所需的数据:

Type itemType = PersonsGrid.ItemsSource.GetType().GetGenericArguments()[0];

var propertyNames = itemType.GetProperties().Select(x => x.Name);