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,并将其修改到示例代码中。
正在踌躇,忽然间一眼发现了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,并将其修改到示例代码中。
相关文章推荐
- [Java] Convert Between the Two, String[] and ArrayList<String>
- C# IEnumerable<T>、IEnumerator<T>、List<T>、ArrayList、[]数组各各的区别
- 【C#基础知识】——List<T>And Dictionary<K,V>泛型集合
- C# IEnumerable<T>、IEnumerator<T>、List<T>、ArrayList、[]数组各各的区别
- C# IEnumerable<T>、IEnumerator<T>、List<T>、ArrayList、[]数组各各的区别
- C# IEnumerable<T>、IEnumerator<T>、List<T>、ArrayList、[]数组各各的区别
- C# IEnumerable<T>、IEnumerator<T>、List<T>、ArrayList、[]数组各各的区别
- C# IEnumerable<T>、IEnumerator<T>、List<T>、ArrayList、[]数组各各的区别
- convert List<String> to a String
- C#中IList<T>与List<T>的区别深入解析
- C#实现 Linq 序列的Distinct—— IEnumerable<T>.Distinct<T>()——IEqualityComparer
- c# 反射得到实体类的字段名称和值,DataTable转List<T>
- C#将DataTable转化为List<T>
- C#:泛型集合—List<T>使用技巧
- [C#基础教程之]C# List<T>用法
- C# List<T>基本用法
- C#中IList<T>与List<T>的区别深入解析
- c#List泛型数据扩展,把List<>型数据格式化成List<SelectListItem>,用来作dropdownlist的数据
- Difference between <? super T> and <? extends T> in Java
- C#中使用BindingList 绑定DataGridView 可以实现动态绑定,优与List<T>集合的绑定