ToList() 还是不 ToList()? [英] To ToList() or not to ToList()?

查看:67
本文介绍了ToList() 还是不 ToList()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个内存(不是 LINQ to SQL)类列表:

Given an in memory (not LINQ to SQL) list of classes:

List<MyClass> myItems = /*lots and lots of items*/;

我使用 GroupBy() 语句分组:

myItems.GroupBy(g => g.Ref)

然后立即在 foreach 循环中使用在组"上调用 .ToList() 是否有任何区别,或者我应该只使用 IEnumerable.

and then immediately consuming in a foreach loop is there any difference in calling .ToList() on the "group" or should I just use an IEnumerable.

完整的代码示例:

List<List<MyClass>> groupedItemsA = new List<List<MyClass>>();
List<List<MyClass>> groupedItemsB = new List<List<MyClass>>();

List<MyClass> myItems = /*lots and lots of items*/;
List<IGrouping<string, MyClass>> groupedItems = myItems.GroupBy(g => g.Ref).ToList();
foreach(IGrouping<string, MyClass> item in groupedItems)
{
  if (/*check something*/)
  {
     groupedItemsA.Add(item.ToList());
  }
  else
  {
    groupedItemsB.Add(item.ToList());
  }
}

List<List<MyClass>> groupedItemsA = new List<List<MyClass>>();
List<List<MyClass>> groupedItemsB = new List<List<MyClass>>();


List<MyClass> myItems = /*lots and lots of items*/;
IEnumerable<IGrouping<string, MyClass>> groupedItems = myItems.GroupBy(g => g.Ref);
foreach(IGrouping<string, MyClass> item in groupedItems)
{
  if (/*check something*/)
  {
     groupedItemsA.Add(item.ToList());
  }
  else
  {
    groupedItemsB.Add(item.ToList());
  }
}

这些幕后"的执行计划有什么不同吗?这两者中的任何一个会更有效还是无关紧要?

Is there any difference in the execution plan of these "under the hood"? Would either of these be more efficient or does it not really matter?

在此之后使用 groupedItems 列表.

I am not using the groupedItems list after this.

推荐答案

是的,有区别,而且可能很重要.

Yes there is a difference and it can be significant.

ToList() 将迭代并将每个迭代项附加到一个新列表中.这具有创建消耗内存的临时列表的效果.

ToList() will iterate and append each iterated item into a new list. This has the effect of creating a temporary list which consumes memory.

有时您可能想要承担内存损失,特别是如果您打算多次迭代列表并且原始列表不在内存中.

Sometimes you might want to take the memory penalty especially if you intend on iterating the list multiple times and the original list is not in memory.

在您使用 ToList() 的特定示例中,您实际上最终迭代了两次 - 一次构建列表,第二次在 foreach 中.根据列表的大小和您的应用程序,这可能是也可能不是问题.

In your particular example using the ToList() you actually end up iterating twice - once to build the list and a second time in your foreach. Depending on the size of the list and your application this may or may not be a concern.

这篇关于ToList() 还是不 ToList()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆