4

正如您从下面的代码中看到的那样,正在从列表中的列表中构建对象集合。想知道是否有更好的方法来编写这种讨厌的方法。

提前喝彩

private List<ListINeed> GetListINeed(Guid clientId)
         {
         var listINeed = new List<objectType>();
             someobject.All(p =>
                                 {
                                     p.subcollection.All(q =>
                                                        {
                                                            listINeed.Add(q.subObject);
                                                            return true;
                                                        });
                                     return true;
                                 });
             return listINeed;
         }
4

3 回答 3

5

使用SelectMany

private List<ListINeed> GetListINeed(Guid clientId)
{
    return someobject.SelectMany(p=> p.subcollection)
                             .Select(p=>p.subObject).ToList();
}
于 2012-11-29T11:50:56.403 回答
1

如果您对使用查询语法感兴趣,您会这样做。

var query = from c in someObject
            from o in c.subCollection
            select o;

这使得在某些情况下阅读起来更好一些,例如

var query = from c in someObject
            from o in c.subCollection
            where c.SomeValue > 12
            select o;

真的是个人喜好,我只是觉得查询语法更容易阅读。:)

于 2012-11-29T12:23:32.130 回答
0

怎么样

return someobject.SelectMany(so=>so.subcollection).Select(o=>o.subObject).ToList();

这实际上几乎否定了对函数的需求,除非您打算在其中做其他事情(如 clientId 参数所暗示的那样)。

于 2012-11-29T11:53:08.080 回答