How to convert an ArrayList to a strongly typed generic list without using a foreach?

前端 未结 4 1737
野趣味
野趣味 2020-12-04 15:05

See the code sample below. I need the ArrayList to be a generic List. I don\'t want to use foreach.

ArrayList arrayList = GetArra         


        
相关标签:
4条回答
  • 2020-12-04 15:43

    This is inefficient (it makes an intermediate array unnecessarily) but is concise and will work on .NET 2.0:

    List<int> newList = new List<int>(arrayList.ToArray(typeof(int)));
    
    0 讨论(0)
  • 2020-12-04 15:52

    Try the following

    var list = arrayList.Cast<int>().ToList();
    

    This will only work though using the C# 3.5 compiler because it takes advantage of certain extension methods defined in the 3.5 framework.

    0 讨论(0)
  • 2020-12-04 16:05

    In .Net standard 2 using Cast<T> is better way:

    ArrayList al = new ArrayList();
    al.AddRange(new[]{"Micheal", "Jack", "Sarah"});
    List<int> list = al.Cast<int>().ToList();
    

    Cast and ToList are extension methods in the System.Linq.Enumerable class.

    0 讨论(0)
  • 2020-12-04 16:07

    How about using an extension method?

    From http://www.dotnetperls.com/convert-arraylist-list:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    
    static class Extensions
    {
        /// <summary>
        /// Convert ArrayList to List.
        /// </summary>
        public static List<T> ToList<T>(this ArrayList arrayList)
        {
            List<T> list = new List<T>(arrayList.Count);
            foreach (T instance in arrayList)
            {
                list.Add(instance);
            }
            return list;
        }
    }
    
    0 讨论(0)
提交回复
热议问题