Return the enumerable as a Collection of T, copying if required. Optimized for the common case where it is a Collection of T and avoiding a copy if it implements IList of T. Avoid mutating the return value. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Return the enumerable as a Collection of T, copying if required. Optimized for the common case where it is a Collection of T and avoiding a copy if it implements IList of T. Avoid mutating the return value.

Demo Code

// Copyright (c) Microsoft Corporation.  All rights reserved.
using System.Linq;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;

public class Main{
        /// <summary>
        /// Return the enumerable as a Collection of T, copying if required. Optimized for the common case where it is 
        /// a Collection of T and avoiding a copy if it implements IList of T. Avoid mutating the return value.
        /// </summary>
        public static Collection<T> AsCollection<T>(this IEnumerable<T> enumerable)
        {/* w ww  . j  a va2s . com*/
            Contract.Assert(enumerable != null);

            Collection<T> collection = enumerable as Collection<T>;
            if (collection != null)
            {
                return collection;
            }
            // Check for IList so that collection can wrap it instead of copying
            IList<T> list = enumerable as IList<T>;
            if (list == null)
            {
                list = new List<T>(enumerable);
            }
            return new Collection<T>(list);
        }
}

Related Tutorials