您的位置:首页 > 编程语言 > C#

C# Freely convert between IList<T> and IEnumerable<T>

2010-11-17 16:28 811 查看
项目中有一处用到将List<T>连接起来。可是在调用Concat方法后,连接后结果却转换为 IEnumerable<T>,如何将其转换回来?

正在踌躇,忽然间一眼发现了IEnumerable接口竟然已经存在了转换方法:public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source);大喜!

附,一示例:

代码

IList<Student> studentList1 = new List<Student>();

Student s1 = new Student();

s1.ID = "1";

s1.Name = "张三";

studentList1.Add(s1);

IList<Student> studentList2 = new List<Student>();

Student s2 = new Student();

s2.ID = "2";

s2.Name = "李四";

studentList2.Add(s2);

List<Student> xxx = studentList1.ToList();

xxx.AddRange(studentList2.ToList());

int c1 = xxx.Count;

IList<Student> yyy = studentList1.Concat(studentList2).ToList<Student>();

int c2 = yyy.Count;

网上示例地址

备注:在同事的提醒下,又发现一转换方法AddRange,并将其修改到示例代码中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: