Linq Query获取对象

时间:2017-02-24 12:42:23

标签: c# linq

public class Parent
{
    public Child Child1 { get; set; }
    public Child Child2 { get; set; }
    public Child Child3 { get; set; }
}
public class Child
{
    public string Name { get; set; }
}

对linq来说有点新鲜。

想要使用反射

检索所有的名称值,即Child1,Child2,Child3

以下是我从反思中看到的方式。

父p = new Parent();

p.Child1.GetType()的GetProperties()ToList();

1 个答案:

答案 0 :(得分:2)

以下似乎对我有用。

class Parent
{
    public Child Child1 { get; set; }
    public Child Child2 { get; set; }
    public Child Child3 { get; set; }
}

public class Child
{
    public string Name { get; set; }
}

public class Tests
{
    public void Test()
    {
        var parent = new Parent();
        parent.Child1 = new Child() { Name = "Child1" };
        parent.Child2 = new Child() { Name = "Child2" };
        parent.Child3 = new Child() { Name = "Child3" };

        var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;

        var names = "";

        parent.GetType() 
            .GetProperties(bindingFlags) //Gets All Properties where the bindingFlags are matching
            .Where(w => w.PropertyType == typeof(Child)) //Filters all properties to type of Child
            .ForEach(property => //Then foreach Child Property
            {
                property.GetType()
                    .GetProperties(bindingFlags) //Gets All Properties where the bindingFlags are matching
                    .Where(w => w.Name == "Name") //Filters all properties to Name of 'Name'
                    .ForEach(value => //Then foreach found Property
                    {
                        names += value.GetValue(property); //Gets the Value of Name Property
                    });
            });
        Console.Write(names);
    }
}

输出“Child1Child2Child3”

编辑:(缩短版本)

parent.GetType() 
    .GetProperties(bindingFlags) 
    .Where(w => w.PropertyType == typeof(Child)) 
    .ForEach(property => property.GetType()
        .GetProperties(bindingFlags) 
        .Where(w => w.Name == "Name") 
        .ForEach(value => names += value.GetValue(property)));