Linq到对象C#嵌套类

时间:2012-06-08 19:48:06

标签: c# linq-to-objects

public class parent
{
    public string abc { get; set; }
    public childclass pos { get; set; }
}

public class childclass
{
    public string value { get; set; }
}

我目前正在阅读父类的集合

var obj =
(from dia in parent
    select new
    {
        abc = dia.abc,
        pos = new childclass()
        {
            value = dia.pos.value
        },
    })
.ToList();

如何使用linq to object读取嵌套类子类,此部分无法正常工作

pos = new childclass()
{
    Value = dia.pos.Value
}, 

请告知

2 个答案:

答案 0 :(得分:1)

C#区分大小写。班级value中的childClass字段有一个小写的“v”。您的LINQ语句使用大写的“V”引用它。

请尝试以下代码:

var obj = (from dia in parent
            select new
            {
                abc = dia.abc,
                pos = new childclass()
                {
                    value = dia.pos.value // 'Value' has been changed to 'value'
                },
            }).ToList();

这是我运行的测试,用于验证更新的LINQ语句是否有效:

var parents = new List<parent>()
{
    new parent{abc = "abc", pos = new childclass{ value = "value" }}
};
var obj =
            (from dia in parents // changed to 'parents' to match my variable above
            select new
            {
                abc = dia.abc,
                pos = new childclass()
                {
                    value = dia.pos.value
                },
            }).ToList();

foreach (var par in obj)
{
    Console.WriteLine(par);
}

结果输出为:

"{ abc = abc, pos = ProgrammingTestBed.Program+childclass }"

答案 1 :(得分:1)

它完美无缺,我认为你的问题是区分大小写的

类:

public class Parent
{
    public string Abc { get; set; }

    public Childclass Pos { get; set; }
}

public class Childclass
{
    public string Value { get; set; }
}

使用:

var parent = new List<Parent> {                
    new Parent { Abc = "abc1", Pos = new Childclass { Value = "Value1" } },
    new Parent { Abc = "abc2", Pos = new Childclass { Value = "Value2" } }
};

var obj =(from dia in parent select new {
                abc = dia.Abc,
                pos = new Childclass()
                {
                    Value = dia.Pos.Value
                },
        }).ToList();