C#中List、Path、字符串操作等常用方法总结

发布于:2025-08-18 ⋅ 阅读:(10) ⋅ 点赞:(0)

一、 List

1. 创建与初始化​​

  • 空列表​​:List numbers = new List();
  • ​​初始化元素​​:List names = new List { “Alice”, “Bob” };
  • ​​指定容量​​:List values = new List(100);(预分配内存,减少扩容开销)

​​2. 增删改查​​

  • ​​添加元素​​:
    Add(10):末尾添加单个元素。
    AddRange(new[] { 20, 30 }):批量添加元素。

  • ​​删除元素​​:
    Remove(20):删除第一个匹配项。
    RemoveAt(1):按索引删除。
    RemoveAll(x => x > 5):删除所有符合条件的元素。

  • ​​修改元素​​:通过索引直接赋值,如numbers[0] = 100;。

  • ​​查找元素​​:
    Contains(10):判断是否存在。
    IndexOf(20):返回首个匹配项的索引。
    Find(x => x % 2 == 0):查找符合条件的第一个元素。

​​3. 排序与反转​​

  • ​​排序​​:
    Sort():默认升序(需元素实现IComparable接口)。
    Sort((a, b) => b.CompareTo(a)):自定义降序。
  • 反转​​:Reverse()

4. 转换与复制​​

  • ​​转数组​​:ToArray()。
  • ​​复制到数组​​:CopyTo(new int[5])。
  • ​​批量复制​​:List.CopyTo方法。

​​5. 遍历与统计​​

  • ​​遍历​​:
    foreach (var item in list):推荐,简洁高效。
    for (int i = 0; i < list.Count; i++):需索引时使用。
  • ​​统计​​:
    Count:元素数量。
    Capacity:当前容量(可动态调整)。
using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static void Main()
    {
        List<int> numbers = new List<int>();
 
        // 添加元素
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);
 
        // 插入元素
        numbers.Insert(2, 4);
 
        // 查找元素
        bool contains3 = numbers.Contains(3); // 返回 true
        int indexOf4 = numbers.IndexOf(4); // 返回 2
 
        // 移除元素
        numbers.Remove(2);
        numbers.RemoveAt(0);
 
        // 统计和求和
        int sum = numbers.Sum(); // 使用默认的加法选择器
        double average = numbers.Average(); // 使用默认的加法选择器
 
        // 打印结果
        Console.WriteLine("Sum: " + sum);
        Console.WriteLine("Average: " + average);
 
        // 转换和复制
        int[] array = numbers.ToArray();
        numbers.CopyTo(array);
 
        // 排序和反转
        numbers.Sort();
        numbers.Reverse();
 
        // 打印排序和反转后的结果
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

二、 Path

1. 路径组合与分解​​

  • ​​Path.Combine(params string[] paths)​​
    合并多个路径段为完整路径,自动处理分隔符(如C:\folder+ file.txt→ C:\folder\file.txt)。
  • ​​Path.GetDirectoryName(string path)​​
    获取路径的目录部分(不含末尾分隔符),如C:\folder\file.txt→ C:\folder。
  • ​​ Path.GetFileName(string path)​​
    获取路径的文件名(含扩展名),如C:\folder\file.txt→ file.txt。
  • ​​Path.GetFileNameWithoutExtension(string path)​​
    获取文件名(不含扩展名),如file.txt→ file。
  • ​​Path.GetExtension(string path)​​
    获取文件扩展名(含.),如file.txt→ .txt。

2. 路径转换与判断​​

  • ​​Path.GetFullPath(string path)​​
    将相对路径转换为绝对路径,解析…等相对符号。
  • ​​Path.IsPathRooted(string path)​​
    判断路径是否为绝对路径(如C:`为绝对路径,folder`为相对路径)。
  • ​​Path.GetPathRoot(string path)​​
    获取路径的根目录(如C:`的根为C:`,\server\share的根为\server\share)。

3. 路径操作与工具​​

  • Path.ChangeExtension(string path, string extension)​​
    更改文件扩展名(如file.txt→ file.md),原扩展名会被替换。
  • ​​Path.GetTempPath()​​
    返回系统临时文件夹路径(如C:\Windows\Temp)。
  • ​​Path.GetTempFileName()​​
    在临时文件夹中创建唯一临时文件并返回路径(如C:\Temp\tmp123.tmp)。

4. 注意事项​​

1.​​参数校验​​:需检查路径是否为null或空字符串,避免抛出异常。
2.​​跨平台兼容​​:Path类自动适配不同操作系统的路径分隔符(Windows为`,Linux/macOS为/`)。
3.​​路径格式化​​:Combine不会合并多个连续分隔符,GetFullPath会规范化路径(如C:\folder\…\file→ C:\file)。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string folderPath = @"C:\example";
        string fileName = "file.txt";

        // 合并路径
        string fullPath = Path.Combine(folderPath, fileName);
        Console.WriteLine($"Full Path: {fullPath}");

        // 获取目录名
        string directoryName = Path.GetDirectoryName(fullPath);
        Console.WriteLine($"Directory Name: {directoryName}");

        // 获取文件名
        string file = Path.GetFileName(fullPath);
        Console.WriteLine($"File Name: {file}");

        // 获取不含扩展名的文件名
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
        Console.WriteLine($"File Name Without Extension: {fileNameWithoutExtension}");

        // 获取扩展名
        string extension = Path.GetExtension(fullPath);
        Console.WriteLine($"Extension: {extension}");

        // 更改扩展名
        string newFullPath = Path.ChangeExtension(fullPath, ".md");
        Console.WriteLine($"New Full Path with Extension .md: {newFullPath}");

        // 获取绝对路径
        string fullPathAbsolute = Path.GetFullPath(fileName);
        Console.WriteLine($"Full Absolute Path: {fullPathAbsolute}");

        // 获取临时文件夹路径
        string tempPath = Path.GetTempPath();
        Console.WriteLine($"Temp Path: {tempPath}");

        // 创建临时文件
        string tempFile = Path.GetTempFileName();
        Console.WriteLine($"Temp File: {tempFile}");
    }
}

三、 字符串操作

1. ​​定义与访问​​

  • 定义:string str = “Hello, World!”;
  • 访问字符:char c = str[0]; // ‘H’
  • 长度:int len = str.Length; // 13

2. ​​拼接​​

  • +运算符:string s = “A” + “B”; // “AB”
  • String.Concat:string s = string.Concat(“A”, “B”, “C”);
  • StringBuilder(高效拼接大量字符串):
StringBuilder sb = new StringBuilder();
sb.Append("A").Append("B");
string s = sb.ToString();

3. ​​子字符串​​

  • Substring(startIndex, length):提取指定位置和长度的子串。
string s = "Hello".Substring(1, 3); // "ell"

4. ​​大小写转换​​

  • ToUpper():转大写。
  • ToLower():转小写。
string s = "Hello".ToUpper(); // "HELLO"

5. ​​查找​​

  • IndexOf(char/substring):返回首次出现的位置(未找到返回-1)。
  • LastIndexOf:返回最后一次出现的位置。
int index = "Hello".IndexOf('l'); // 2

6. ​​替换​​

  • Replace(oldValue, newValue):替换字符或子串。
string s = "Hello".Replace('l', 'x'); // "Hexxo"

7. ​​正则表达式​​

  • Regex.IsMatch:验证字符串是否符合模式(如邮箱、手机号)。
  • Regex.Replace:复杂替换(如提取数字)。
using System.Text.RegularExpressions;
bool isValidEmail = Regex.IsMatch("test@example.com", @"^\w+@\w+\.\w+$");

8.​​格式化​​

  • ​​插值字符串​​(C# 6.0+):string s = $“Name: {name}, Age: {age}”;

  • String.Format:string s = string.Format(“Name: {0}, Age: {1}”, name, age);

9. ​​分割​​

  • Split(char/delimiter):按分隔符拆分字符串为数组。
string[] fruits = "apple,banana,orange".Split(','); // ["apple", "banana", "orange"]

10. ​​去除空格​​

  • Trim():去除首尾空格。
  • TrimStart() / TrimEnd():分别去除首部/尾部空格。
string s = "  Hello  ".Trim(); // "Hello"

11. 填充字符​​

  • PadLeft/PadRight(totalWidth, paddingChar):在左侧/右侧填充指定字符至指定长度。
string s = "123".PadLeft(5, '0'); // "00123"

12. ​​比较与判断​​

  • Equals:比较两个字符串是否相等(可忽略大小写)。
  • StartsWith/EndsWith:判断是否以指定字符开头/结尾。
bool isStartWith = "Hello".StartsWith("H"); // true