Search code examples
c#collectionsienumerable

Convert IEnumerable to Collection (not ICollection)


Linq returns IEnumerable and the code has a Collection. How to assign the return value of a Linq operation to a Collection variable?

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var myList = new List<string> {"item"};
            Collection<string> myCollection = myList.Select(x => x);

            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}

Notes:

  1. About not using Collection, I can't change it.
  2. Assigning List to Collection throws casting error.
  3. The following works somehow, any better alternative?

Collection<string> myCollection = new Collection(myList.Select(x => x).ToList());


Solution

  • If you have to work with Collection<T> why not implementing an extension method in order to use it with Linq:

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    
    ...
    
    public static partial class EnumerableExtensions {
      public static Collection<T> ToCollection<T>(this IEnumerable<T> source) {
        if (source is null)
          throw new ArgumentNullException(nameof(source));
    
        Collection<T> result = new Collection<T>();
    
        foreach (T item in source)
          result.Add(item);
    
        return result; 
      }
    } 
    

    Then you can use it as simple as

    var myCollection = myList
      .Select(item => item) //TODO: Put actual query here 
      .ToCollection();