System.Collections.Generic.List<T>

作者:追风剑情 发布于:2021-1-21 17:38 分类:C#

System.Collections.Generic.List<T>的方法总结

List<T>类官方文档
List<T>扩展方法官方文档

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApp21
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. int[] intArr = new int[3] { 100, 101, 102 };
  14. int[] intArrRange = new int[2] { 10, 11 };
  15.  
  16. List<int> list = new List<int>();
  17. list.Capacity = 20;
  18. list.AddRange(intArr);//添加集合
  19. for (int i = 0; i < 5; i++)
  20. list.Add(i);//添加单个元素
  21. //在0号位置插入一个元素
  22. list.Insert(0, 99);
  23. //在1号位置插入一个集合
  24. list.InsertRange(1, intArrRange);
  25.  
  26. //list能容纳的元素个数(List会自动调整这个大小)
  27. Console.WriteLine("Capacity: {0}", list.Capacity);
  28. Console.WriteLine("Count: {0}", list.Count);
  29.  
  30. //返回只读集合
  31. IList<int> readOnlyList = list.AsReadOnly();
  32. //改变list中的元素会同时影响readOnlyList
  33. list.Add(1000);
  34.  
  35. //获取指定范围的元素
  36. List<int> range = list.GetRange(1, 5);
  37.  
  38. Console.WriteLine("\n排序前:");
  39. //遍历只读集合
  40. foreach (int i in readOnlyList)
  41. Console.Write(i + " ");
  42.  
  43. //排序
  44. list.Sort((a, b) => {
  45. if (a > b) return 1;
  46. else if (a == b) return 0;
  47. return -1;
  48. });
  49.  
  50. Console.WriteLine("\n排序后:");
  51. //遍历只读集合
  52. foreach (int i in readOnlyList)
  53. Console.Write(i + " ");
  54.  
  55. Console.WriteLine("\n反转元素");
  56. //返转所有元素
  57. list.Reverse();
  58. //反转指定范围的元素
  59. //list.Reverse(int index, int count);
  60. //遍历只读集合
  61. foreach (int i in readOnlyList)
  62. Console.Write(i + " ");
  63.  
  64. //删除前面两个元素
  65. list.RemoveRange(0, 2);
  66. list.Remove(1000);
  67. list.RemoveAt(0);
  68. Console.WriteLine("\nForEach:");
  69. //遍历所有元素
  70. list.ForEach(delegate(int a)
  71. {
  72. Console.Write(a + " ");
  73. });
  74.  
  75. //判断是否包含某个元素
  76. Console.WriteLine("\nContains(1000): {0}", readOnlyList.Contains(1000));
  77.  
  78. //判断是否包含满足某种条件的元素
  79. Console.WriteLine("Exists(>=99): {0}", list.Exists(x => x >= 99));
  80.  
  81. //判断所有元素是否满足某种条件
  82. bool IsTrueForAll = list.TrueForAll(a=> { return a >= 0; });
  83. Console.WriteLine("IsTrueForAll: {0}", IsTrueForAll);
  84.  
  85. //将列表中的每个元素转成另一种类型
  86. List<object> objList = list.ConvertAll<object>(new Converter<int, object>(
  87. input=> { return (object)input; }));
  88. //注意,无法直接转List
  89. //List<object> objList = list;
  90.  
  91. int[] targetArr = new int[20];
  92. //将元素复制到目标数组中
  93. list.CopyTo(targetArr);
  94. //重载版本
  95. //list.CopyTo(0, targetArr, 0, list.Count);
  96.  
  97. //返回数组
  98. int[] array = list.ToArray();
  99.  
  100. //寻找指定元素所在索引号,未找到返回-1
  101. int indexOf = list.IndexOf(100);
  102. int lastIndexOf = list.LastIndexOf(100);
  103. Console.WriteLine("IndexOf(100): {0}", indexOf);
  104. Console.WriteLine("LastIndexOf(100): {0}", lastIndexOf);
  105.  
  106. //搜索满足条件的第一个元素
  107. int element = list.Find(x => x == 99);
  108. Console.WriteLine("Find(99): {0}", element);
  109.  
  110. //从后往前搜索
  111. int elementLast = list.FindLast(x => x == 99);
  112.  
  113. //搜索满足条件的所有元素, 以下三种写法等效
  114. List<int> elements = list.FindAll(x => x == 99);
  115. //List<int> elements = list.FindAll(x => { return x == 99; });
  116. //List<int> elements = list.FindAll(delegate (int x) { return x == 99; });
  117.  
  118. //搜索满足条件第一个元素的索引号
  119. int indexFirst = list.FindIndex(x => x == 99);
  120. //从后往前搜索
  121. int indexLast = list.FindLastIndex(x => x == 99);
  122.  
  123. Console.WriteLine("升序排列");
  124. list.Sort();
  125. foreach (int i in list)
  126. Console.Write(i + " ");
  127. Console.WriteLine();
  128. //BinarySearch()适合对已排序的大集合进行搜索
  129. //使用默认的比较器(Comparer<int>.Default)
  130. int binarySearchIndex = list.BinarySearch(10);
  131. //int binarySearchIndex = list.BinarySearch(10, Comparer<int>.Default);
  132. Console.WriteLine("BinarySearch(10): {0}", binarySearchIndex);
  133. int binarySearchIndex1 = list.BinarySearch(10, new ListComparer<int>());
  134. Console.WriteLine("binarySearchIndex1(10): {0}", binarySearchIndex1);
  135.  
  136. /*------------- List 扩展方法 -------------*/
  137. //求平均值
  138. double average = list.Average();
  139. //求总和
  140. int sum = list.Sum();
  141. //求最大值
  142. int max = list.Max();
  143. //求最小值
  144. int min = list.Min();
  145. //返回满足条件的元素个数
  146. long longCount = list.LongCount(x => x > 5);
  147. int count = list.Count(x => x > 5);
  148. //累加器,将所有偶数相加
  149. int aggregate = list.Aggregate(
  150. (total, next) => next % 2 == 0 ? total + next : total);
  151. //测试是否所有元素都满足条件
  152. bool all = list.All(x => x >= 0);
  153. //测试是否存在满足条件的元素
  154. bool any = list.Any(x => x == 100);
  155.  
  156. Console.WriteLine("Average: {0}", average);
  157. Console.WriteLine("Sum: {0}", sum);
  158. Console.WriteLine("Max: {0}", max);
  159. Console.WriteLine("Min: {0}", min);
  160. Console.WriteLine("LongCount(>5): {0}", longCount);
  161. Console.WriteLine("Aggregate(): {0}", aggregate);
  162. Console.WriteLine("All(>=0): {0}", all);
  163. Console.WriteLine("Any(=100): {0}", any);
  164.  
  165. //追加元素
  166. //list.Append(5);
  167. //返回枚举器
  168. IEnumerable<int> query = list.AsEnumerable();
  169. //foreach (int i in query)
  170. // Console.WriteLine(i);
  171. //强制转换成指定类型,转换失败会抛出InvalidCastException
  172. IEnumerable<object> cast = list.Cast<object>();
  173. //连接其他集合
  174. IEnumerable<int> concat = list.Concat(query);
  175. //是否包含某个元素
  176. //list.Contains(100);//使用默认比较器
  177. //使用自定义比较器
  178. bool b1 = list.Contains(100, new CustomEqualityComparer());
  179. //如果list为空,则返回一个带默认值的IEnumerable<>
  180. IEnumerable<int> enumerable = list.DefaultIfEmpty(0);
  181. //返回非重复元素集合
  182. IEnumerable<int> distinct = list.Distinct();//使用默认比较器
  183. IEnumerable<int> distinct1 = list.Distinct(new CustomEqualityComparer());
  184. //返回指定位置的元素
  185. int elementAt = list.ElementAt(0);
  186. int elementAtOrDefault = list.ElementAtOrDefault(0);//default(TSource)
  187. //返回一个空集合
  188. IEnumerable<int> empty = Enumerable.Empty<int>();
  189. //生成两个集合的差集
  190. int[] number1 = { 99, 100 };
  191. //从list中返回不包含number1元素的集合
  192. IEnumerable<int> except = list.Except(number1);//使用默认比较器
  193. IEnumerable<int> except1 = list.Except(number1, new CustomEqualityComparer());
  194. //反回满足条件的第一个元素
  195. int first = list.First(x => x > 5);
  196. //int first = list.First();//直接返回第1个元素
  197. int firstDefault = list.FirstOrDefault(x => x > 5);//default(TSource)
  198. //int firstDefault = list.FirstOrDefault();
  199. //返回满足条件的最后一个元素
  200. //list.Last(x => x > 5);
  201. //list.Last();
  202. //list.LastOrDefault(x => x > 5);
  203. //list.LastOrDefault();
  204.  
  205. Console.WriteLine("\nGroupBy:");
  206. //对集合分组
  207. var query1 = list.GroupBy(
  208. //key,这里将元素分为奇数组和偶数组
  209. x => x % 2 == 0 ? "even" : "odd",
  210. //对每个元素做处理,这里直接返回x
  211. x => x,
  212. //组处理函数(key, 集合)
  213. (key, intArray) => new
  214. {
  215. Key = key,
  216. Value = intArray.Count() //被分配到key组的元素个数
  217. });
  218. foreach(var result in query1)
  219. {
  220. Console.WriteLine("Key={0}, Value={1}", result.Key, result.Value);
  221. }
  222.  
  223. Console.WriteLine("\nGroupJoin:");
  224. //连接分组,以list中的元素为key对join集合元素进行分组
  225. List<int> join = new List<int>() { 200, 201, 202 };
  226. var query2 = list.GroupJoin(
  227. //inner
  228. join,
  229. //计算outerKey
  230. x => x % 2,
  231. //计算innerKey
  232. y => y % 2,
  233. //当innerKey==outerKey时,当前y属性x分组
  234. (x, yCollection) => new
  235. {
  236. Key = x,
  237. Value = yCollection
  238. });
  239. foreach (var result in query2)
  240. {
  241. Console.Write("x={0}: ", result.Key);
  242. foreach (int y in result.Value)
  243. Console.Write(y + " ");
  244. Console.WriteLine();
  245. }
  246.  
  247. Console.WriteLine("\nIntersect:");
  248. //返回两个集合的交集
  249. List<int> iontersect = new List<int>() { 99, 100, 200 };
  250. var query3 = list.Intersect(iontersect);
  251. foreach (int i in query3)
  252. Console.Write(i + " ");
  253.  
  254. Console.WriteLine("\nJoin:");
  255. var query4 = list.Join(
  256. //inner
  257. join,
  258. //计算outerKey
  259. x => x % 2,
  260. //计算innerKey
  261. y => y % 2,
  262. //当innerKey==outerKey时,触发此回调
  263. //即,基于公共键关联两个信息源
  264. (x, y)=> new {
  265. Key=x, Value=y
  266. });
  267. foreach(var obj in query4)
  268. {
  269. Console.WriteLine("Key={0}, Value={1}", obj.Key, obj.Value);
  270. }
  271.  
  272. Console.WriteLine("\nOfType:");
  273. //从集合中筛选出指定类型的元素
  274. var query5 = list.OfType<int>();
  275.  
  276. //对元素按升序排序
  277. IEnumerable<int> query6 = list.OrderBy(x=>x);
  278. //对元素按降序排序
  279. IEnumerable<int> query7 = list.OrderByDescending(x => x);
  280.  
  281. //在列表的开头添加元素
  282. //list.Prepend(0);
  283.  
  284. Console.WriteLine("\nRange:");
  285. //从5开始生成10个元素
  286. IEnumerable<int> range1 = Enumerable.Range(5, 10);
  287. foreach (int i in range1)
  288. Console.Write(i+" ");
  289.  
  290. Console.WriteLine("\nRepeat:");
  291. //生成10个值为-1的元素
  292. IEnumerable<int> range2 = Enumerable.Repeat(-1, 10);
  293. foreach (int i in range2)
  294. Console.Write(i + " ");
  295.  
  296. Console.WriteLine("\nWhere:");
  297. //返回满足条件的集合
  298. IEnumerable<int> query8 = list.Where(x=>x>50);
  299.  
  300. //反转元素顺序
  301. list.Reverse();
  302.  
  303. Console.WriteLine("\nSelect:");
  304. //将所有元素投影到新集合中
  305. var select = list.Select((x, index) => new {
  306. index = index,
  307. value = x
  308. });
  309. foreach (var obj in select)
  310. Console.WriteLine("index={0}, value={1}", obj.index, obj.value);
  311.  
  312. Console.WriteLine("\nSelectMany:");
  313. SelectManyEx3();
  314.  
  315. Console.WriteLine("\nSequenceEqual:");
  316. //比较两个集合是否相等
  317. List<int> equal = new List<int>() { 1,2 };
  318. bool b2 = list.SequenceEqual(equal);//使用默认比较器
  319.  
  320. Console.WriteLine("\nSingle:");
  321. //返回序列中满足指定条件的唯一元素;如果有多个这样的元素存在,则会引发异常。
  322. int element1 = list.Single(x=>x<1);
  323. int element2 = list.SingleOrDefault(x=>x<0);
  324.  
  325. Console.WriteLine("\nSkip:");
  326. //跳过前3个元素,返回一个新集合
  327. IEnumerable<int> query9 = list.Skip(3);
  328. //省略后3个元素,返回一个新集合
  329. //IEnumerable<int> query10 = list.SkipLast(3);
  330.  
  331. //返回条件判断为false的元素
  332. IEnumerable<int> query11 = list.SkipWhile(x => x >= 80);
  333.  
  334. //返回前3个元素
  335. IEnumerable<int> query12 = list.Take(3);
  336. //返回后3个元素
  337. //IEnumerable<int> query13 = list.TakeLast(3);
  338.  
  339. //返回条件判断为true的元素
  340. IEnumerable<int> query13 = list.TakeWhile(x=>x>80);
  341.  
  342. //list.ToHashSet();
  343. List<int> list1 = list.ToList();
  344.  
  345. Console.WriteLine("\nUnion:");
  346. //返回非重复元素的并集
  347. List<int> union = new List<int>() { 1,2,400};
  348. IEnumerable<int> query14 = list.Union(union);
  349.  
  350. TakeByEx();
  351. ToDictionaryEx1();
  352. ToLookupEx1();
  353. ZipEx();
  354.  
  355. //仅保留元素实际所占用的内存空间
  356. list.TrimExcess();
  357. //清空列表
  358. list.Clear();
  359.  
  360. Console.ReadLine();
  361. }
  362.  
  363. //官方示例
  364. public static void SelectManyEx3()
  365. {
  366. PetOwner[] petOwners = {
  367. new PetOwner { Name="Higa",
  368. Pets = new List<string>{ "Scruffy", "Sam" } },
  369. new PetOwner { Name="Ashkenazi",
  370. Pets = new List<string>{ "Walker", "Sugar" } },
  371. new PetOwner { Name="Price",
  372. Pets = new List<string>{ "Scratches", "Diesel" } },
  373. new PetOwner { Name="Hines",
  374. Pets = new List<string>{ "Dusty" } } };
  375.  
  376. // Project the pet owner's name and the pet's name.
  377. var query = petOwners.SelectMany(
  378. //理解成一级遍历
  379. //遍历集合中的每个元素
  380. petOwner => petOwner.Pets,
  381. //理解成二级遍历
  382. //遍历Pets集合 (petName是Pets中的元素)
  383. (petOwner, petName) => new { petOwner, petName })
  384. //End SelectMany
  385.  
  386. //-- 继续筛选 --
  387. //返回以S开头的宠物名称集合
  388. .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
  389. //返回一个新集合
  390. .Select(ownerAndPet =>
  391. new
  392. {
  393. Owner = ownerAndPet.petOwner.Name,
  394. Pet = ownerAndPet.petName
  395. }
  396. );
  397.  
  398. // Print the results.
  399. foreach (var obj in query)
  400. {
  401. Console.WriteLine(obj);
  402. }
  403. }
  404.  
  405. //官方示例
  406. public static void TakeByEx()
  407. {
  408. string[] fruits = { "grape", "passionfruit", "banana", "mango",
  409. "orange", "raspberry", "apple", "blueberry" };
  410.  
  411. // Sort the strings first by their length and then
  412. //alphabetically by passing the identity selector function.
  413. //OrderBy为一级排序,ThenBy在一级排序的基础上排序
  414. IEnumerable<string> query =
  415. fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);
  416.  
  417. /*
  418. IEnumerable<string> query1 =
  419. fruits
  420. .OrderBy(fruit => fruit.Length)
  421. //降序排序
  422. .ThenByDescending(fruit => fruit);
  423. */
  424.  
  425. foreach (string fruit in query)
  426. {
  427. Console.WriteLine(fruit);
  428. }
  429.  
  430. /*
  431. This code produces the following output:
  432.  
  433. apple
  434. grape
  435. mango
  436. banana
  437. orange
  438. blueberry
  439. raspberry
  440. passionfruit
  441. */
  442. }
  443.  
  444. //List转Dictionary
  445. public static void ToDictionaryEx1()
  446. {
  447. List<Package> packages =
  448. new List<Package>
  449. { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L },
  450. new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L },
  451. new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L },
  452. new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } };
  453.  
  454. // Create a Dictionary of Package objects,
  455. // using TrackingNumber as the key.
  456. Dictionary<long, Package> dictionary =
  457. packages.ToDictionary(p => p.TrackingNumber);
  458.  
  459. foreach (KeyValuePair<long, Package> kvp in dictionary)
  460. {
  461. Console.WriteLine(
  462. "Key {0}: {1}, {2} pounds",
  463. kvp.Key,
  464. kvp.Value.Company,
  465. kvp.Value.Weight);
  466. }
  467. }
  468.  
  469. //List转查找表(Lookup)
  470. public static void ToLookupEx1()
  471. {
  472. // Create a list of Packages.
  473. List<Package> packages =
  474. new List<Package>
  475. { new Package { Company = "Coho Vineyard",
  476. Weight = 25.2, TrackingNumber = 89453312L },
  477. new Package { Company = "Lucerne Publishing",
  478. Weight = 18.7, TrackingNumber = 89112755L },
  479. new Package { Company = "Wingtip Toys",
  480. Weight = 6.0, TrackingNumber = 299456122L },
  481. new Package { Company = "Contoso Pharmaceuticals",
  482. Weight = 9.3, TrackingNumber = 670053128L },
  483. new Package { Company = "Wide World Importers",
  484. Weight = 33.8, TrackingNumber = 4665518773L } };
  485.  
  486. // Create a Lookup to organize the packages.
  487. // Use the first character of Company as the key value.
  488. // Select Company appended to TrackingNumber
  489. // as the element values of the Lookup.
  490. ILookup<char, string> lookup =
  491. packages
  492. .ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)),
  493. p => p.Company + " " + p.TrackingNumber);
  494.  
  495. // Iterate through each IGrouping in the Lookup.
  496. foreach (IGrouping<char, string> packageGroup in lookup)
  497. {
  498. // Print the key value of the IGrouping.
  499. Console.WriteLine(packageGroup.Key);
  500. // Iterate through each value in the
  501. // IGrouping and print its value.
  502. foreach (string str in packageGroup)
  503. Console.WriteLine(" {0}", str);
  504. }
  505. }
  506.  
  507. //合并两个序列
  508. public static void ZipEx()
  509. {
  510. int[] numbers = { 1, 2, 3, 4 };
  511. string[] words = { "one", "two", "three" };
  512.  
  513. var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
  514.  
  515. foreach (var item in numbersAndWords)
  516. Console.WriteLine(item);
  517. }
  518. }
  519.  
  520. //自定义二叉搜索比较器
  521. public class ListComparer<T> : IComparer<T> where T : IComparable
  522. {
  523. //这里的比较方式要与List中的元素排序方式一致
  524. //例如:List中的元素是升序的,这里的判断也必须是升序的
  525. public int Compare(T x, T y)
  526. {
  527. if (x == null)
  528. return y != null ? -1 : 0;
  529. if (y == null)
  530. return 1;
  531. if (x is T && y is T)
  532. return x.CompareTo(y);
  533. return 0;
  534. }
  535. }
  536.  
  537. //自定义相等比较器
  538. class CustomEqualityComparer : IEqualityComparer<int>
  539. {
  540. public bool Equals(int x, int y)
  541. {
  542. return x == y;
  543. }
  544.  
  545. public int GetHashCode(int obj)
  546. {
  547. return obj.GetHashCode();
  548. }
  549. }
  550.  
  551. class PetOwner
  552. {
  553. public string Name { get; set; }
  554. public List<string> Pets { get; set; }
  555. }
  556.  
  557. class Package
  558. {
  559. public string Company { get; set; }
  560. public double Weight { get; set; }
  561. public long TrackingNumber { get; set; }
  562. }
  563. }

运行测试
1111.png
2222.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号