Re: List<T> constructor taking IEnumerable<T> behaves surprisingly

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Marc Gravell

    Re: List<T> constructor taking IEnumerable<T> behaves surprisingly

    You could bypass the List<T>'s tendency to use ICollection<Tby
    simply not giving it an ICollection<T- for example, with the C# 3
    extension method below you could use:

    List<Tlist = new List<T>(source. AsEnumerableOnl y());

    The AsEnumerableOnl y() *only* exposes IEnumerable<T(O K, it also
    exposes IEnumerable and IDisposable ;-p), allowing your non-Count-
    friendly implementation to work happily.

    Marc

    public static class EnumerableExt
    {
    public static IEnumerable<TAs EnumerableOnly< T>(
    this IEnumerable<Tso urce)
    {
    if (source == null) yield break; // GIGO
    foreach (T item in source)
    {
    yield return item;
    }
    }
    }
Working...