Linq选择表达此关键字

时间:2014-08-15 07:04:24

标签: c# linq

在select子句中,可以在select子句中指向其他级别对象,或者是否有任何特殊关键字指向。如果不是,我怎么能用select子句来解决这个问题。

list.Select(o => new ParentClass {
   ID = o.ID,                            
   ChildClass = o.Childs.Select(p => new ChildClass { 
                                     Parent = @this,
                                     ID = p.id 
                               }).ToList()
});

2 个答案:

答案 0 :(得分:6)

不,你不能。因为尚未创建ParentClass实例。您需要以下内容。

list.Select(o =>
{ 
   var parent = new ParentClass
    {
        ID = o.ID
    };
    parent.ChildClass = o.Childs
                        .Select(p =>
                           new ChildClass 
                           { 
                               Parent = parent,
                               ID = p.id 
                           })
                         .ToList();
     return parent;
});

答案 1 :(得分:3)

使用对象初始化程序无法执行此操作。

list.Select(o => 
    {
        var pc = new ParentClass();
        pc.ID = o.ID;
        pc.ChildClass = o.Childs.Select(p => new ChildClass 
            { 
                Parent = pc,
                ID = p.id 
            }).ToList();
        return pc;
    });