1 class Program 2 { 3 static void Main(string[] args) 4 { 5 /* 6 * List遍历删除 或取指定的前N项 7 */ 8 List<PerSon> listPer = CreateListPer(); 9 10 // 1、输出项 11 Console.WriteLine("输出listPer项"); 12 foreach (PerSon per in listPer) 13 { 14 Console.WriteLine("Id:" + per.Id + " Name:" + per.name); 15 } 16 17 //2、删除15条之后的数据 18 //遍历删除索引大于50的项 19 //将listPer的项复制到listPerTemp里面 如果直接用“=”的话,listPerTemp删除索引大于15的项,listPer大于15的项也会删掉 20 List<PerSon> listPerTemp = new List<PerSon>(listPer.ToArray()); 21 //这将复制listPer中的所有项目到listPerTemp 22 //listPer.ForEach(i => listPerTemp.Add(i)); 23 listPer.ForEach(i => listPerTemp.Add(i)); 24 for (int i = listPerTemp.Count - 1; i >= 0; i--) 25 { 26 if (i >= 15) 27 { 28 listPerTemp.RemoveAt(i); 29 } 30 } 31 Console.Write("\n"); 32 // 3、输出项 33 Console.WriteLine("输出listPerTemp项"); 34 foreach (PerSon per in listPerTemp) 35 { 36 Console.WriteLine("Id:" + per.Id + " Name:" + per.name); 37 } 38 39 // 40 Console.Write("\n"); 41 Console.WriteLine("输出listPer项"); 42 foreach (PerSon per in listPer) 43 { 44 Console.WriteLine("Id:" + per.Id + " Name:" + per.name); 45 } 46 47 Console.Write("\n"); 48 //除了用移除的方法获取索引小于15的项,还可以用.take(15); 49 var result = from r in listPer 50 select r; 51 52 result = result.Take(15); 53 foreach (var c in result) 54 { 55 Console.WriteLine("Id:" + c.Id + " Name:" + c.name); 56 } 57 58 Console.Write("\n"); 59 //或者直接take 60 listPer = listPer.Take(15).ToList(); 61 foreach (PerSon per in listPer) 62 { 63 Console.WriteLine("Id:" + per.Id + " Name:" + per.name); 64 } 65 Console.ReadKey(); 66 } 67 68 private static List<PerSon> CreateListPer() 69 { 70 List<PerSon> listper = new List<PerSon>(); 71 PerSon per = new PerSon(); 72 for (int i = 1; i <= 20; i++) 73 { 74 per = new PerSon(); 75 per.Id = i; 76 per.name = "N-" + i; 77 listper.Add(per); 78 } 79 80 return listper; 81 } 82 } 83 84 public class PerSon 85 { 86 /// <summary> 87 /// 编号 88 /// </summary> 89 public int Id { get; set; } 90 91 /// <summary> 92 /// 名称 93 /// </summary> 94 public string name { get; set; } 95 }