private IEnumerable<string> Tables
{
get
{
yield return "Foo";
yield return "Bar";
}
}
假设我想要迭代这些并写一些类似于processing #n of #m的东西。
有没有一种方法可以让我在不进行主迭代的情况下求出m的值?
我希望我讲清楚了。
private IEnumerable<string> Tables
{
get
{
yield return "Foo";
yield return "Bar";
}
}
假设我想要迭代这些并写一些类似于processing #n of #m的东西。
有没有一种方法可以让我在不进行主迭代的情况下求出m的值?
我希望我讲清楚了。
当前回答
我认为这是最简单的方法
Enumerable.Count<TSource>(IEnumerable<TSource> source)
参考:system.linq.enumerable
其他回答
我使用这样的代码,如果我有字符串列表:
((IList<string>)Table).Count
你可以使用System.Linq。
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
private IEnumerable<string> Tables
{
get {
yield return "Foo";
yield return "Bar";
}
}
static void Main()
{
var x = new Test();
Console.WriteLine(x.Tables.Count());
}
}
你会得到结果'2'。
只是增加了一些额外的信息:
Count()扩展并不总是迭代。考虑Linq to Sql,其中计数将进入数据库,但不是返回所有行,而是发出Sql count()命令并返回结果。
此外,编译器(或运行时)足够聪明,如果有对象的Count()方法,它将调用该方法。所以这并不像其他回应者所说的那样,完全无知,总是为了计算元素而迭代。
在许多情况下,程序员只是检查if(可枚举的。Count != 0)使用Any()扩展方法,如if(enumerable.Any())使用linq的惰性求值要有效得多,因为一旦确定有任何元素,它就会短路。它的可读性也更强
IEnumerable<T>上的System.Linq.Enumerable.Count扩展方法有以下实现:
ICollection<T> c = source as ICollection<TSource>;
if (c != null)
return c.Count;
int result = 0;
using (IEnumerator<T> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
result++;
}
return result;
因此,它尝试强制转换为具有Count属性的ICollection<T>,并尽可能使用该属性。否则它会迭代。
因此,最好的方法是在IEnumerable<T>对象上使用Count()扩展方法,因为这样可以获得最好的性能。
LINQ中有一个用于。net 6的新方法 观看https://www.youtube.com/watch?v=sIXKpyhxHR8
Tables.TryGetNonEnumeratedCount(out var count)