有没有办法记住或物化一个IEnumerable? [英] Is there a way to Memorize or Materialize an IEnumerable?

查看:110
本文介绍了有没有办法记住或物化一个IEnumerable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当给定一个 D 你可以处理像一个列表或数组中,AST将列举一些外部数据源,甚至是AST上现有的一些固定顺序采集。有没有办法安全地兑现的枚举所以喜欢的foreach枚举的操作,计数等不执行AST每一次?

When given an d you could be dealing with a fixed sequence like a list or array, an AST that will enumerate some external datasource, or even an AST on some existing collection. Is there a way to safely "materialize" the enumerable so that enumeration operations like foreach, count, etc. don't execute the AST each time?

我常常已经使用 .ToArray()来创建这个represenation但如果底层的存储已经是一个列表或其他固定的顺序,这似乎是浪费复制。这将是很好,如果我能做到

I've often used .ToArray() to create this represenation but if the underlying storage is already a list or other fixed sequence, that seems like wasted copying. It would be nice if i could do

var enumerable = someEnumerable.Materialize();

if(enumberable.Any() {
  foreach(var item in enumerable) {
    ...
  }
} else {
  ...
}

而不必担心。任何()的foreach 试图枚举序列两次,没有它unccessarily复制枚举。

Without having to worry that .Any() and foreach try to enumerate the sequence twice and without it unccessarily copying the enumerable.

推荐答案

很容易的:

public static IList<TSource> Materialize<TSource>(this IEnumerable<TSource> source)
{
    if (source is IList<TSource>)
    {
        // Already a list, use it as is
        return (IList<TSource>)source;
    }
    else
    {
        // Not a list, materialize it to a list
        return source.ToList();
    }
}

这篇关于有没有办法记住或物化一个IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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