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的值?
我希望我讲清楚了。
当前回答
我在一个方法中使用了这样的方法来检查传入的IEnumberable内容
if( iEnum.Cast<Object>().Count() > 0)
{
}
在这样的方法中:
GetDataTable(IEnumberable iEnum)
{
if (iEnum != null && iEnum.Cast<Object>().Count() > 0) //--- proceed further
}
其他回答
它可能不会产生最好的性能,但你可以使用LINQ来计算IEnumerable中的元素:
public int GetEnumerableCount(IEnumerable Enumerable)
{
return (from object Item in Enumerable
select Item).Count();
}
我在一个方法中使用了这样的方法来检查传入的IEnumberable内容
if( iEnum.Cast<Object>().Count() > 0)
{
}
在这样的方法中:
GetDataTable(IEnumberable iEnum)
{
if (iEnum != null && iEnum.Cast<Object>().Count() > 0) //--- proceed further
}
不,不一般。使用枚举对象的一点是,枚举中的实际对象集是不知道的(预先知道,甚至根本不知道)。
除了你的直接问题(已经得到了否定的回答),如果你想在处理一个可枚举对象时报告进度,你可能想看看我的博客文章《在Linq查询期间报告进度》。
它让你这样做:
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (sender, e) =>
{
// pretend we have a collection of
// items to process
var items = 1.To(1000);
items
.WithProgressReporting(progress => worker.ReportProgress(progress))
.ForEach(item => Thread.Sleep(10)); // simulate some real work
};
我使用这样的代码,如果我有字符串列表:
((IList<string>)Table).Count