前言
在C#开发中,字符串、数组和集合是处理数据的三大核心工具。本文将深入剖析它们的特性和使用技巧,并配合大量实用代码示例,助你掌握这些关键数据结构的高效用法。无论是处理文本数据还是管理复杂数据集,这些知识都将成为你的开发利器。
一、字符串(String)处理
1.1 字符串的不可变性
C#字符串是不可变对象,所有修改操作都会生成新字符串对象:
string s1 = "Hello";
string s2 = s1; // s2指向同一内存地址
s1 += " World"; // 创建新对象,s1指向新地址
Console.WriteLine(s2); // 输出"Hello"(原对象未改变)
1.2 常用字符串操作
▶ 拼接与格式化
// 使用$字符串插值(C# 6+)
string name = "Alice";
int age = 25;
string info = $"{name} is {age} years old.";
// String.Format方法
string msg = String.Format("当前时间:{0:yyyy-MM-dd}", DateTime.Now);
▶ 分割与合并
string csv = "apple,banana,orange";
string[] fruits = csv.Split(','); // 分割为数组
string merged = string.Join("|", fruits); // 合并为"apple|banana|orange"
▶ 查找与替换
string text = "The quick brown fox jumps over the lazy dog";
int index = text.IndexOf("fox"); // 返回15
bool contains = text.Contains("lazy"); // true
string newText = text.Replace("dog", "cat"); // 替换单词
▶ 截取与修剪
string url = " https://example.com/path/ ";
string trimmed = url.Trim(); // 去除首尾空格
string domain = url.Substring(8, 7); // 截取"example"
1.3 高性能字符串处理
使用StringBuilder
处理频繁修改的字符串(避免内存浪费):
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.Append(i.ToString() + " ");
}
string result = sb.ToString();
二、数组(Array)
2.1 一维数组
// 声明与初始化
int[] numbers = new int[5]; // 默认值0填充
string[] colors = { "Red", "Green", "Blue" };
// 动态赋值
numbers[0] = 10;
numbers[1] = 20;
// 遍历数组
foreach (var color in colors) {
Console.WriteLine(color);
}
2.2 多维数组
▶ 矩形数组
int[,] matrix = new int[3, 2] {
{1, 2},
{3, 4},
{5, 6}
};
Console.WriteLine(matrix[1, 1]); // 输出4
▶ 交错数组(数组的数组)
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };
Console.WriteLine(jagged[1][2]); // 输出5
2.3 数组工具方法
Array.Sort(numbers); // 排序
Array.Reverse(numbers); // 反转
int max = numbers.Max(); // 获取最大值(需using System.Linq)
三、集合(List<T>与Dictionary<TKey, TValue>)
3.1 List<T>动态数组
▶ 基本操作
List<string> cities = new List<string>();
cities.Add("Beijing"); // 添加元素
cities.AddRange(new[] { "Shanghai", "Guangzhou" });
cities.Remove("Shanghai");// 删除元素
// 索引访问
Console.WriteLine(cities[0]); // 输出"Beijing"
// 遍历
foreach (var city in cities) {
Console.WriteLine(city);
}
▶ 高级功能
// 条件查找
var match = cities.Find(c => c.StartsWith("B")); // 返回"Beijing"
// 排序
cities.Sort(); // 默认按字母排序
cities.OrderByDescending(c => c.Length).ToList(); // LINQ排序
// 容量优化
cities.TrimExcess(); // 释放多余内存
3.2 Dictionary<TKey, TValue>键值对集合
▶ 基本用法
Dictionary<string, int> population = new Dictionary<string, int>();
population.Add("Beijing", 21_540_000);
population["Shanghai"] = 24_870_000; // 索引器添加
// 安全访问
if (population.TryGetValue("Guangzhou", out int value)) {
Console.WriteLine(value);
}
// 遍历键值对
foreach (var kvp in population) {
Console.WriteLine($"{kvp.Key}: {kvp.Value}万人");
}
▶ 特性与技巧
// 键的唯一性验证
if (!population.ContainsKey("Shenzhen")) {
population.Add("Shenzhen", 12_530_000);
}
// 删除元素
population.Remove("Beijing");
// 性能说明:查找时间复杂度接近O(1)
3.3 集合初始化器
简化集合创建语法:
List<int> scores = new List<int> { 90, 85, 78 };
Dictionary<string, string> config = new Dictionary<string, string> {
["Theme"] = "Dark",
["Language"] = "Chinese"
};
四、综合实战:学生成绩管理系统
public class Student {
public string Name { get; set; }
public Dictionary<string, int> Scores { get; set; }
}
class Program {
static void Main() {
List<Student> students = new List<Student> {
new Student {
Name = "Alice",
Scores = new Dictionary<string, int> {
["Math"] = 90,
["English"] = 85
}
},
new Student {
Name = "Bob",
Scores = new Dictionary<string, int> {
["Math"] = 78,
["English"] = 92
}
}
};
// 查询数学成绩高于80的学生
var mathTop = students.Where(s => s.Scores["Math"] > 80)
.Select(s => s.Name);
Console.WriteLine($"数学优秀:{string.Join(", ", mathTop)}");
// 添加新科目成绩
foreach (var student in students) {
student.Scores.Add("Physics", new Random().Next(60, 100));
}
}
}
五、性能与最佳实践
-
字符串:
-
优先使用
StringBuilder
处理超过3次修改的字符串 -
使用
string.IsNullOrEmpty()
进行空值检查
-
-
数组与集合:
-
需要固定大小时用数组,动态数据用List<T>
-
预估List容量时可指定初始大小:
new List<int>(1000)
-
Dictionary的键建议使用不可变类型(如string、int)
-
-
集合选择指南:
场景 推荐集合类型 快速查找 Dictionary 顺序访问/频繁修改 List 去重元素 HashSet 先进先出 Queue
六、扩展学习
-
更多集合类型:
-
HashSet<T>
(唯一元素集合) -
Stack<T>
(后进先出) -
LinkedList<T>
(双向链表)
-
-
LINQ查询:
var highScores = students.SelectMany(s => s.Scores.Values) .Where(score => score > 85) .OrderByDescending(s => s);
-
源码参考: