List<T>的常用操作
001-合并两个集合
List<int> listA = new List<int> { 1, 2, 3, 4, 5, 7, 9 }; List<int> listB = new List<int> { 17, 4, 13, 9, 2 }; List<int> Result1 = listA.Union(listB).ToList<int>(); //剔除重复项 List<int> Result2 = listA.Concat(listB).ToList<int>(); //保留重复项
----------------------------------------------------------------------------------------------------
002-集合中的元素,用某个字符串连起来。效果:1,2,3,4,5,7,9
还可以只把复杂类型的List中的某个字段/属性连接
有一个数据结构
public class Student { public int ID { get; set; } public string Name { get; set; } }
List<int> list1 = new List<int> { 1, 2, 3, 4, 5, 7, 9 }; string result1 = string.Join(",", list1); //结果:1,2,3,4,5,7,9
List<Student> list2 = new List<Student>(); for (int i = 0; i < 5; i++) { list2.Add(new Student() { ID = i, Name = "SW" + i.ToString() }); } string result2 = string.Join(",", list2.Select(t => t.Name));
//结果:SW0,SW1,SW2,SW3,SW4