C# 获得 IEnumerable<T> 计数的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 08:17:47  来源:igfitidea点击:

The best way to get a count of IEnumerable<T>

提问by Sean Chambers

Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection?

在不枚举集合中的所有项目的情况下,获取 IEnumerable 集合中的项目数的最佳/最简单的方法是什么?

Possible with LINQ or Lambda?

可以使用 LINQ 或 Lambda 吗?

采纳答案by Brian Leahy

You will have to enumerate to get a count. Other constructs like the List keep a running count.

您必须枚举才能计数。其他结构如 List 保持运行计数。

回答by Konrad Rudolph

In any case, you have to loop through it. Linq offers the Countmethod:

无论如何,您必须循环遍历它。Linq 提供了Count方法:

var result = myenum.Count();

回答by Greg Hurlman

Not possible with LINQ, as calling .Count(...) does enumerate the collection. If you're running into the problem where you can't iterate through a collection twice, try this:

LINQ 不可能,因为调用 .Count(...) 会枚举集合。如果您遇到无法遍历集合两次的问题,请尝试以下操作:

List<MyTableItem> myList = dataContext.MyTable.ToList();
int myTableCount = myList.Count;

foreach (MyTableItem in myList)
{
   ...
}

回答by Joel Coehoorn

There's also IList or ICollection, if you want to use a construct that is still somewhat flexible, but also has the feature you require. They both imply IEnumerable.

还有 IList 或 ICollection,如果您想使用仍然有点灵活但又具有您需要的功能的构造。它们都意味着 IEnumerable。

回答by ICR

The solution depends on why you don't want to enumerate through the collection.

解决方案取决于您不想枚举集合的原因。

If it's because enumerating the collection might be slow, then there is no solution that will be faster. You might want to consider using an ICollection instead if possible. Unless the enumeration is remarkably slow (e.g. it reads items from disk) speed shouldn't be a problem though.

如果是因为枚举集合可能很慢,那么没有更快的解决方案。如果可能,您可能需要考虑使用 ICollection。除非枚举非常慢(例如它从磁盘读取项目),否则速度应该不是问题。

If it's because enumerating the collection will require more code then it's already been written for you in the form of the .Count() extension method. Just use MyEnumerable.Count().

如果是因为枚举集合需要更多代码,那么它已经以 .Count() 扩展方法的形式为您编写。只需使用 MyEnumerable.Count()。

If it's because you want to be able to enumerate the collection after you've counted then the .Count() extension method allows for this. You can even call .Count() on a collection you're in the middle of enumerating and it will carry on from where it was before the count. For example:

如果是因为您希望能够在计数后枚举集合,那么 .Count() 扩展方法允许这样做。您甚至可以对正在枚举的集合调用 .Count() ,它会从计数之前的位置继续。例如:

foreach (int item in Series.Generate(5))
{
    Console.WriteLine(item + "(" + myEnumerable.Count() + ")");
}

will give the results

会给结果

0 (5)

1 (5)

2 (5)

3 (5)

4 (5)

0 (5)

1 (5)

2 (5)

3 (5)

4 (5)

If it's because the enumeration has side effects (e.g. writes to disk/console) or is dependant on variables that may change between counting and enumerating (e.g. reads from disk) [N.B. If possible, I would suggest rethinking the architecture as this can cause a lot of problems] then one possibility to consider is reading the enumeration into an intermittent storage. For example:

如果是因为枚举有副作用(例如写入磁盘/控制台)或依赖于可能在计数和枚举之间发生变化的变量(例如从磁盘读取)[注意如果可能,我建议重新考虑架构,因为这可能会导致很多问题] 那么要考虑的一种可能性是将枚举读入间歇性存储。例如:

List<int> seriesAsList = Series.Generate(5).ToList();

All of the above assume you can't change the type (i.e. it is returned from a library that you do not own). If possible you might want to consider changing to use an ICollection or IList (ICollection being more widely scoped than IList) which has a Count property on it.

以上所有假设您不能更改类型(即它是从您不拥有的库中返回的)。如果可能,您可能需要考虑更改为使用具有 Count 属性的 ICollection 或 IList(ICollection 的范围比 IList 更广泛)。

回答by Keith

If you need to count and then loop you may be better off with a list.

如果您需要计数然后循环,最好使用列表。

If you're using count to check for members you can use Any()to avoid enumerating the entire collection.

如果您使用 count 来检查成员,则可以使用它Any()来避免枚举整个集合。

回答by Moustafa Deif

The best solution -as I think is to do the following:

最好的解决方案 - 我认为是执行以下操作:

  1. using System.Linq.Dynamic;
  2. myEnumerable.AsQueryable().Count()
  1. 使用 System.Linq.Dynamic;
  2. myEnumerable.AsQueryable().Count()

回答by Soundararajan

It also depends on what you want to achieve by counting.. If you are interested to find if the enumerable collection has any elements, you could use

这也取决于你想通过计数实现什么..如果你有兴趣找出可枚举集合是否有任何元素,你可以使用

myEnumerable.Any() over myEnumerable.Count() where the former will yield the first element and the later will yield all the elements.

myEnumerable.Any() 在 myEnumerable.Count() 上,前者将产生第一个元素,后者将产生所有元素。

回答by Mukesh

Use this.

用这个。

IEnumerable list =..........;

list.OfType<T>().Count()

it will return the count.

它会返回计数。

回答by Timmy Fuller

An IEnumerable will have to iterate through every item. to get the full count. If you just need to check if there is one or more items in an IEnumerable a more efficient method is to check if there are any. Any() only check to see there is a value and does not loop through everything.

IEnumerable 必须遍历每个项目。得到完整的计数。如果您只需要检查 IEnumerable 中是否有一个或多个项目,则更有效的方法是检查是否有。Any() 仅检查是否存在值,而不会遍历所有内容。

IEnumerable myStrings = new List(){"one","two", "three"};

IEnumerable myStrings = new List(){"一","二","三"};

bool hasValues = myStrings.Any();

bool hasValues = myStrings.Any();