有没有更好的方法编写以下方法?也许使用LINQ?
除了声明一个新列表然后使用一个foreach来填充列表之外,还有没有更好的方法可以使用LINQ在一行中做到这一点?

public IEnumerable<RoleAreasModel> GetRolesWithRoleAreasModelByUserGUID(Guid guid)
    {
      IList<RoleAreasModel> rolesWithRoleAreas = new List<RoleAreasModel>();
      foreach (AspnetRolesRecord role in GetByUserGUID(guid))
      {
        RoleAreasRecord roleAreaRecord = RoleAreasService.Instance.GetRecord(RoleAreasRecord.Fields.ID, role.ID);
        rolesWithRoleAreas.Add(new RoleAreasModel(roleAreaRecord.Area, new RolesMapper().MapToModel(role), getAreaControllersData(roleAreaRecord.ID)));
      }
      return rolesWithRoleAreas;
    }

最佳答案

public IEnumerable<RoleAreasModel> Foo(Guid id)
{
   var mapper = new RolesMapper();
   return from role in GetByUserGUID(id)
          let areaRecord = RoleAreasService.Instance.GetRecord(RoleAreasRecord.Fields.ID, role.ID)
          select new RoleAreasModel(areaRecord.Area, mapper.MapToModel(role), getAreaControllersData(areaRecord.ID));
}


希望能帮助到你。

10-06 00:35