如何将Ilist转换为ArrayList?

我可以将IList转换为ArrayList吗?

如果是的话我该怎么办?

 IList alls = RetrieveCourseStudents(cf); ArrayList a = (ArrayList)alls; 

那是对的吗?

有错误:

无法转换类型的对象

这完全是关于多态性的。 ArrayList是Interface IList的一个实现。

  IList iList = new ArrayList(); 

变量iList中的静态类型是IList,但它引用了一个ArrayList对象!

从IList到ArrayList没有真正的转换,因为您无法从Interface或abstract Class实例化/创建Object。

正如评论中所建议的那样,您应该考虑使用generics集合

 List students = RetrieveCourseStudents(cf).Cast().ToList() 

如果已经是ArrayList ,则只能将alls转换为ArrayList ,即RetrieveCourseStudents返回的对象是ArrayList

如果不是那么你需要创建一个新对象,幸运的是ArrayList有一个构造函数可以做到这一点: new ArrayList(RetrieveCourseStudents(cf))


值得注意的是,您现在应该使用generics(例如List )而不是ArrayList ,所以除非您需要与一些无法更新的旧代码进行交互,否则我将远离它。

是的,只有当RetrieveCourseStudents(cf)返回Arraylist的类型时,我们才能将IList强制转换为ArrayList。

例如

 static void Main(string[] args) { IList test1 = GetList(); IList test2= GetIList(); ArrayList list1 = (ArrayList)test1; // Fails ArrayList list2 = (ArrayList)test2; // Passes Console.ReadKey(); } private static IList GetIList() { return new ArrayList(); } private static IList GetList() { return new CustomList(); } 

由于您评论说您只想订购返回的列表(在另一个注释中,您说的是EntityCollection类型) – 您不需要转换为ArrayList而只需直接使用该值。

您可以使用OrderBy LINQ扩展方法(以及您使用的变量类型 – IList也不适用)。

这将适合您的需求( CourseStudentPropertyCourseStudentProperty的属性):

 var alls = RetrieveCourseStudents(cf); var orderedAlls = alls.OrderBy(cs => cs.CourseStudentProperty); 
 using System; using System.Collections; using System.Collections.Generic; namespace MyILists { class Program { static void Main(string[] args) { IList intArrayList = new ArrayList().ToIList(); intArrayList.Add(1); intArrayList.Add(2); //intArrayList.Add("Sample Text"); // Will not compile foreach (int myInt in intArrayList) { Console.WriteLine(" Number : " + myInt.ToString()); } Console.Read(); } } public static class MyExtensions { public static IList ToIList(this ArrayList arrayList) { IList list = new List(arrayList.Count); foreach (T instance in arrayList) { list.Add(instance); } return list; } } } 

只需使用这个简单的代码:)

 (From x In list).ToArray 

您可以使用LINQ Union扩展。

请注意,您可以将任何类型的IEnumerable与此技术(Array,IList等)结合使用,因此您无需担心“添加”方法。 您必须了解LINQ正在生成不可变结果,因此您需要使用“ToList()”,“ToDictionary()”或其他任何内容,如果您想随后操作集合。

  var list = (IList) new [] { new Student {FirstName = "Jane"}, new Student {FirstName = "Bill"}, }; var allStudents = list.Union( new [] {new Student {FirstName = "Clancey"}}) .OrderBy(s => s.FirstName).ToList(); allStudents[0].FirstName = "Billy"; foreach (var s in allStudents) { Console.WriteLine("FirstName = {0}", s.FirstName); } 

输出:

 FirstName = Billy FirstName = Clancey FirstName = Jane