17人参与 • 2026-08-03 • Asp.net
在c#中,list<t> 是一个非常常用的泛型集合类,属于 system.collections.generic 命名空间。list<t> 提供了一种灵活的方式来存储和管理一组元素,这些元素可以是任何类型的对象。下面,我们将详细解析 list<t> 的特性、使用方法、以及一些高级应用。
list<t> 是 c# 中最常用的泛型集合类,位于 system.collections.generic 命名空间。它代表一个强类型、可动态调整大小的对象列表,提供了丰富的操作方法,是数组(array)的现代化替代品。
t 确保集合中只能存储指定类型的元素。list[0]。// 创建空列表
list<string> names = new list<string>();
// 创建并初始化
list<int> numbers = new list<int> { 1, 2, 3, 4, 5 };
// 指定初始容量(优化性能)
list<double> values = new list<double>(100);list<string> fruits = new list<string>();
fruits.add("apple"); // 添加单个元素
fruits.addrange(new string[] { "banana", "orange" }); // 添加多个元素
fruits.insert(1, "mango"); // 在指定位置插入list<int> scores = new list<int> { 85, 92, 78 };
int firstscore = scores[0]; // 85
scores[1] = 95; // 修改第二个元素
// 遍历列表
foreach (int score in scores)
{
console.writeline(score);
}
// 使用 foreach 方法
scores.foreach(s => console.writeline($"score: {s}"));list<string> colors = new list<string> { "red", "green", "blue", "red" };
colors.remove("red"); // 删除第一个匹配项
colors.removeat(0); // 删除指定位置的元素
colors.removeall(c => c.startswith("b")); // 删除所有满足条件的元素
colors.clear(); // 清空列表| 方法/属性 | 说明 | 示例 |
|---|---|---|
count | 获取元素数量 | int count = list.count; |
add(t item) | 添加元素到末尾 | list.add("item"); |
addrange(ienumerable<t>) | 添加多个元素 | list.addrange(array); |
insert(int index, t item) | 在指定位置插入 | list.insert(0, "first"); |
remove(t item) | 删除第一个匹配项 | list.remove("target"); |
removeat(int index) | 删除指定位置元素 | list.removeat(0); |
contains(t item) | 检查是否包含元素 | bool has = list.contains("x"); |
indexof(t item) | 查找元素索引 | int idx = list.indexof("x"); |
sort() | 排序(默认升序) | list.sort(); |
reverse() | 反转元素顺序 | list.reverse(); |
toarray() | 转换为数组 | t[] arr = list.toarray(); |
linkedlist<t>。capacity 属性:一次性添加大量元素前,可设置合适的容量。addrange 而非循环 add。asreadonly() 返回只读视图。| 特性 | list<t> | array |
|---|---|---|
| 大小 | 动态调整 | 固定长度 |
| 性能 | 插入/删除可能需移动元素 | 随机访问最快 |
| 内存 | 有额外开销(容量管理) | 最紧凑 |
| 功能 | 丰富的内置方法 | 基本操作 |
| 适用场景 | 元素数量变化频繁 | 大小固定、性能要求高 |
// 从数据库读取用户列表
list<user> users = dbcontext.users.tolist();
// 使用 linq 筛选
list<user> activeusers = users
.where(u => u.isactive)
.orderby(u => u.name)
.tolist();public class cachemanager<t>
{
private list<t> _cache = new list<t>();
public void additem(t item) => _cache.add(item);
public t getitem(predicate<t> match) => _cache.find(match);
}list<t> 是 c# 开发中不可或缺的集合类型,它结合了数组的索引访问优势和动态集合的灵活性。掌握其基本操作、性能特性和适用场景,能显著提升代码质量和开发效率。在实际项目中,应根据具体需求选择合适的集合类型,list<t> 通常是处理可变序列时的首选。
到此这篇关于c#中list<t>泛型集合类的全面解析与应用的文章就介绍到这了,更多相关c# list<t>内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论