在新语句中动态分配属性

时间:2012-10-30 08:24:32

标签: c# .net

我想在新语句中使用foreach循环分配属性subdecision_typex_value,它是DtoReport类的属性。

这有可能吗?它有意义吗?

public DtoReport Get(Report repResp)
   return new DtoReport()
   {
      archivingId = repResp.archivingId.ToString(),
      dateCreated = DateTime.Now,

      //I'D LIKE TO DO IT THAT WAY IS IT POSSIBLE SOMEHOW ?
      foreach(Subdecision d in repResp.decisionMatrix.subdecisions){
         if(d.type == "SOME VALUE"){
            //Dynamically assign DtoReport subdecision_typex_value Property 
            subdecision_typex_value = d.value                   
         }
      }
      //END

      anotherProperty = repResp.AnotherProperty
   }

1 个答案:

答案 0 :(得分:1)

您可以使用Linq:

return new DtoReport()
{
  archivingId = repResp.archivingId.ToString(),
  dateCreated = DateTime.Now,
  subdecision_typex_value = repResp.decisionMatrix.subdecisions
                           .Where(d => d.type == "SOME VALUE")
                           .Select(d => d.value)
                           .FirstOrDefault(),
  anotherProperty = repResp.AnotherProperty
}

请注意,您的方法很可能不符合预期。您要枚举所有子决策,然后使用type=="SOME VALUE"获取最后一个值。我假设你想要采用这种类型的第一个值,我是对的吗?

相关问题