我应该如何获得IEnumerable的长度? [英] How should I get the length of an IEnumerable?

查看:655
本文介绍了我应该如何获得IEnumerable的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些代码,并获得了IEnumerable的长度.当我写myEnumerable.Count()时,令我惊讶的是,它没有编译.在阅读 IEnumerable Count()和Length 之间的差异后,我意识到这是实际上,Linq给了我扩展方法.

I was writing some code, and went to get the length of an IEnumerable. When I wrote myEnumerable.Count(), to my surprise, it did not compile. After reading Difference between IEnumerable Count() and Length, I realized that it was actually Linq that was giving me the extension method.

使用.Length也不对我编译.我使用的是C#的较旧版本,所以也许这就是原因.

Using .Length does not compile for me either. I am on an older version of C#, so perhaps that is why.

获取IEnumerable长度的最佳实践是什么?我应该使用Linq的Count()方法吗?还是有更好的方法. .Length是否可以在更高版本的C#中使用?

What is the best practice for getting the length of an IEnumerable? Should I use Linq's Count() method? Or is there a better approach. Does .Length become available on a later version of C#?

或者如果我需要计数,那么IEnumerable是工作的错误工具吗?我应该改为使用ICollection吗? 计算IEnumerable< T>中的项目说ICollection是一个解决方案,但是如果您想要一个带计数的IEnumerable,那是正确的解决方案吗?

Or if I need the count, is an IEnumerable the wrong tool for the job? Should I be using ICollection instead? Count the items from a IEnumerable<T> without iterating? says that ICollection is a solution, but is it the right solution if you want an IEnumerable with a count?

强制性代码段:

var myEnumerable = IEnumerable<Foo>();

int count1 = myEnumerable.Length; //Does not compile

int count2 = myEnumerable.Count(); //Requires Linq namespace

int count3 = 0; //I hope not
for(var enumeration in myEnumerable)
{
    count3++;
}

推荐答案

如果您需要读取IEnumerable<T>中的项数,则必须调用扩展方法Count,通常为 (请参阅Matthew的注释)将在序列中对元素进行内部迭代,并将返回序列中的项数.没有其他更直接的方法.

If you need to read the number of items in an IEnumerable<T> you have to call the extension method Count, which in general (look at Matthew comment) would internally iterate through the elements of the sequence and it will return you the number of items in the sequence. There isn't any other more immediate way.

如果知道您的序列是一个数组,则可以使用Length属性将其强制转换并读取它们的项数.

If you know that your sequence is an array, you could cast it and read them number of items using th Length property.

不,在更高版本中没有任何这样的方法.

No, in later versions there isn't any such method.

有关Count方法的实现细节,请查看

For implementation details of Count method, please have a look at here.

这篇关于我应该如何获得IEnumerable的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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