List是C#中常见的可伸缩数组组件,因为是可伸缩的,常常被用来代替数组,不需要手动分配数组大小。
- /* 首先是创建了一个字符串列表,在列表中添加了三个名称,并打印所有大写的名称. */
-
- using System;
- using System.Collections.Generic;
-
-
- namespace list_tutorial
- {
- class Program
- {
- static void Main(string[] args)
- {
- var names = new List<string> {
- "GG","Ana","Felipe"
- };
-
- /*这里是使用字符串内插功能.加个$ 符号,可以将内容打印出来.{name.ToUpper()} 作用是将上面list中的内容全部大写的字母. */
-
- foreach (var name in names)
- {
- Console.WriteLine($"Hello{name.ToUpper()}!");
- }
- }
- }
- }
(1)添加元素、删除元素
(2)添加索引
(3)使用Count确定列表的长度,使用的方法是{names.Count}
(4)使用names.Sort()对list进行排序
- using System;
- using System.Collections.Generic;
-
- namespace list_tutorial
- {
- class Program
- {
- static void Main(string[] args)
- {
- var names = new List<string> {
- "GG","Ana","Felipe"
- };
-
- // add作用是添加
- names.Add("Maria");
- names.Add("Bill");
- //remove作用是删除
- names.Remove("Ana");
-
- foreach (var name in names)
- {
- Console.WriteLine($"Hello{name.ToUpper()}!");
- }
-
- //添加索引
- Console.WriteLine($"My name is {names[0]}");
- }
- }
- }
完整的代码
- using System;
- using System.Collections.Generic;
-
- namespace list_tutorial
- {
- class Program
- {
- static void Main(string[] args)
- {
- WorkingWithStrings();
- }
-
- static void WorkingWithStrings()
- {
- var names = new List<string>{"name", "Ana" , "Felipe"};
- foreach (var name in names)
- {
- Console.WriteLine($"Hello {name.ToUpper()}!");
- }
-
- Console.WriteLine();
- names.Add("Maria");
- names.Add("Bill");
- names.Remove("Ana");
- foreach (var name in names)
- {
- Console.WriteLine($"Hello {name.ToUpper()}!");
- }
-
- Console.WriteLine($"my name is {names[0]}");
- Console.WriteLine($"The list has {names.Count} people in it");
-
- var index = names.IndexOf("Felipe");
- if (index == -1)
- {
- Console.WriteLine($"IndexOf returns {index}");
- }
- else
- {
- Console.WriteLine($"The name {names[index]} is at index {index}");
- }
-
- index = names.IndexOf("Not Found");
- if (index == -1)
- {
- Console.WriteLine($"IndexOf returns {index}");
- }
- else
- {
- Console.WriteLine($"The name {names[index]} is at index {index}");
- }
- names.Sort();
- foreach (var name in names)
- {
- Console.WriteLine($"hello {name.ToUpper()}!");
- }
-
- }
- }
- }