带Select子句的ExpandoObject

时间:2013-01-14 04:51:33

标签: c# linq dynamic types

我必须在Linq Query

中的类下面填充
public class Emp             
{       
    public string name {get; set;}      
    public dynamic Obj { get; set; }       
    public Emp()
    {
        Obj = new ExpandoObject();
    }  
}

public LoadData()  
{
   var emp = (from d in dbContext.Employees         
              select new Emp   
              {  
                 name = d.name,  
                 Obj.DOB = d.DOB,  
                 Obj.BirthPlace = d.BirthPlace  
              }).ToList();

}

OR

    public LoadData()  
    {
       var emp = (from d in dbContext.Employees         
                  select new Emp   
                  {  
                     name = d.name,  
                    Obj.DOB = new ExpandoObject { DOB = d.DOB, BirthPlace =   d.BirthPlace }      }).ToList();

    }

它不允许我像上面那样动态分配属性,任何人都可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

尝试这种方式:

var emp = (from d in dbContext.Employees         
          select new Emp   
          {  
             name = d.name,  
             Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace } 
          }).ToList();

它与@gowansg答案非常相似,但没有new个关键字。它只是设置属性值。如果我们尝试获取Type Obj,我们会收到System.Dynamic.ExpandoObject。使用new关键字,它将是一些匿名类型。 分别是这样的结构:

emp[0].Obj.OtherProperty = 1;
如果使用匿名类型,

将失败。

答案 1 :(得分:0)

您在第二个示例中已经接近了,您只需要将Obj设置为new anonymous object而不是new ExpandoObject

var emp = (from d in dbContext.Employees         
          select new Emp   
          {  
             name = d.name,  
             Obj = new { DOB = d.DOB, BirthPlace = d.BirthPlace }
          }).ToList();

答案 2 :(得分:0)

var emp =(来自dbContext.Employees中的d)           选择新的Emp
          {
             name = d.name,
             Obj = {DOB = d.DOB,BirthPlace = d.BirthPlace}
})ToList();