「マテリアライズ」はこのようなコードの良い名前ですか、それとももっと良い (そして公式の) ものはありますか?
enumerable as ICollection<T> ?? enumerable .ToArray()
編集:コード(およびその目的)を明確にしました
// or "MaterializeIfNecessary"
public static IEnumerable<T> Materialize<T>(this IEnumerable<T> source)
{
// if you use code analysis tools like resharper, you may have to return a
// different type to turn off warnings - even a placeholder interface like
// IMaterializedEnumerable<T> : IEnumerable<T> { }
if (source == null) return null;
return source as ICollection<T> ?? source.ToArray();
}
問題:
static void Save(IEnumerable<string> strings)
{
// The following code is Resharper suggested solution to
// "Possible multiple enumeration of IEnumerable" warning
// ( http://confluence.jetbrains.com/display/ReSharper/Possible+multiple+enumeration+of+IEnumerable ):
strings = strings as string[] ?? strings.ToArray(); // you're not calling
// ToArray because you
// need an array, here
if (strings.Any(s => s.Length >= 255)) throw new ArgumentException();
File.AppendAllLines("my.path.txt", strings);
}
拡張メソッドを使用すると、最初の行がより宣言的になります。
strings = strings.MaterializeIfNecessary();