Return the enumerable as a List of T, copying if required. Optimized for common case where it is an List of T or a ListWrapperCollection of T. Avoid mutating the return value. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Return the enumerable as a List of T, copying if required. Optimized for common case where it is an List of T or a ListWrapperCollection 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 List of T, copying if required. Optimized for common case where it is an List of T 
        /// or a ListWrapperCollection of T. Avoid mutating the return value.
        /// </summary>
        public static List<T> AsList<T>(this IEnumerable<T> enumerable)
        {/*from w ww.  java  2 s.  c o m*/
            Contract.Assert(enumerable != null);

            List<T> list = enumerable as List<T>;
            if (list != null)
            {
                return list;
            }
            ListWrapperCollection<T> listWrapper = enumerable as ListWrapperCollection<T>;
            if (listWrapper != null)
            {
                return listWrapper.ItemsList;
            }
            return new List<T>(enumerable);
        }
}

Related Tutorials