使用LINQ改进方法

时间:2012-03-25 19:17:22

标签: c# linq

有没有更好的方法来编写以下方法?使用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;
    }

3 个答案:

答案 0 :(得分:6)

由于您返回IEnumerable<RoleAreasModel>,为什么不使用yield return而不是创建临时列表?

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

顺便说一下,Eric Lippert写了一篇非常有趣的关于迭代器的博客文章以及它们如何在C#中工作。非常值得一读

http://blogs.msdn.com/b/ericlippert/archive/2009/07/09/iterator-blocks-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/tags/iterators/

答案 1 :(得分:4)

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));
}

希望它有所帮助。

答案 2 :(得分:1)

这个怎么样?

public IEnumerable<RoleAreasModel> GetRolesWithRoleAreasModelByUserGUID(Guid guid)
{
  return GetByUserGUID(guid).Select( role => 
    {
      var roleAreaRecord = RoleAreasService.Instance.GetRecord(RoleAreasRecord.Fields.ID, role.ID);
      return new RoleAreasModel(roleAreaRecord.Area, new RolesMapper().MapToModel(role),getAreaControllersData(roleAreaRecord.ID)));
    });
}