开发者

How to detect if a LINQ enumeration is materialized?

Is there some way of detecting whether an enumerable built using LINQ (to Objects in this case) have been materialized or not? Oth开发者_开发问答er than trying to inspect the type of the underlying collection?

Specifically, since enumerable.ToArray() will build a new array even if the underlying collection already is an array I'm looking for a way of avoiding ToArray() being called twice on the same collection.


The enumerable won't have an "underlying collection", it will be a collection. Try casting it to one and use the resulting reference:

var coll = enumerable as ICollection<T>;
if (coll != null) {
    // We have a collection!
}


Checking "is IEnumerable" can do this, there isn't another way. You could, however, not use the "var" declaration for the return type - because it is "hiding" from you the type. If you declare an explicit IEnumerable, then the compiler will let you know if that is what is being returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜