2010-09-30 195 views
1

是否有更优雅/简洁的方式;我想摆脱WorkListItem初始化代码的foreach循环。IQueryable,将匿名类型转换为强类型

 var queryable = registrations.Select(
      r => new 
        { 
         r.Id, r.AccountNumber, r.DateAdded, r.DateUpdated, r.Patient, r.Patient.InsuranceInfos 
        }); 
     var list = queryable.ToList(); 

     var workListItems = new List<WorkListItem>(); 
     foreach (var anonymous in list) 
     { 
      var w = new WorkListItem 
         { 
          Id = anonymous.Id, 
          ClientAccountId = anonymous.AccountNumber, 
          DateAdded = anonymous.DateAdded, 
          DateUpdated = anonymous.DateUpdated, 
          Patient = anonymous.Patient, 
          InsuraceInfos = anonymous.Patient.InsuranceInfos 
         }; 
      workListItems.Add(w); 
     } 
     return workListItems; 
+0

我假设你已经tryied一个ToList或类似的东西。 .. – sebagomez 2010-09-30 22:44:55

+0

我试过这个,它只是返回一个emapty列表var list = queryable.OfType ()。ToList(); – 2010-09-30 22:46:11

回答

3

是的,你可以完全切断了“中间人”,因为它是和选择直接进入一个新的WorkListItem如下:

var list = registrations.Select(r => new WorkListItem 
      { 
       Id = r.Id, 
       ClientAccountId = r.AccountNumber, 
       DateAdded = r.DateAdded, 
       DateUpdated = r.DateUpdated, 
       Patient = r.Patient, 
       InsuraceInfos = r.Patient.InsuranceInfos 
      }).ToList(); 
+0

甚至可以添加'WorkListItem'类的能力,以便从'registration' – PostMan 2010-09-30 22:51:53

+0

开始投射,谢谢! – 2010-09-30 22:57:36