获取具有父级一个属性的特定类的所有属性

时间:2018-11-02 17:19:59

标签: c# linq c#-4.0

请考虑以下代码:

class ClassA
{
    public int ID { get; set; }
    public string Name { get; set; }
    public ClassA PropA { get; set; }
}

class ClassC
{
    public ClassC()
    {
        var MyVar = new List<ClassA>
        {
            new ClassA()
            {
                ID = 1,
                Name = "Name1",
                PropA = new ClassA()
                {
                    ID = 2,
                    Name = "Name2",
                    PropA = new ClassA()
                    {
                        ID = 3,
                        Name = "Name3",
                        PropA = new ClassA()
                        {
                            ID =4,
                            Name = "Name4",
                            PropA = null,
                        }
                    }

                }
            },
            new ClassA()
            {
                ID = 5,
                Name = "Name5",
                PropA = new ClassA()
                {
                    ID = 6,
                    Name = "Name6",
                    PropA = null,
                }
            },
            new ClassA()
            {
                ID = 7,
                Name = "Name7",
                PropA = null,
            },
            new ClassA()
            {
                ID = 8,
                Name = "Name8",
                PropA = new ClassA()
                {
                    ID = 9,
                    Name = "Name9",
                    PropA = new ClassA()
                    {
                        ID = 10,
                        Name = "Name10",
                        PropA = new ClassA()
                        {
                            ID = 11,
                            Name = "Name11",
                            PropA = null,
                        }
                    }
                }
            },
        };
    }
}

我想获取所有不为null且其父项的name属性为ClassA的属性。例如:

   Parent        Class A
--------------------------------
1)"Name1"     Class A with ID = 2
2)"Name2"     Class A with ID = 3
3)"Name3"     Class A with ID = 4
4)"Name5"     Class A with ID = 6
and...

谢谢

1 个答案:

答案 0 :(得分:2)

您的意思是这样的吗(C#7):

private static IEnumerable<string> Describe(ClassA a)
{
    var (parent, current) = (a, a.PropA);

    while (!(current is null))
    {
        yield return $"{parent.Name}     Class A with ID = {current.ID}";
        (parent, current) = (current, current.PropA);
    }
}
...
var results = MyVar.SelectMany(Describe);

根据注释的要求,C#4版本:

private static IEnumerable<string> DescribeCSharp4(ClassA a)
{
    var parent = a;
    var current = a.PropA;

    while (current != null)
    {
        yield return parent.Name + "     Class A with ID = " + current.ID;

        parent = current;
        current = current.PropA;
    }
}
...
var results = MyVar.SelectMany(DescribeCSharp4);