ASP.NET List
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 List<T> 集合。List 是 .NET 应用程序中用于存储和操作对象集合的基本数据结构。
ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。List<T> 类提供了强大的方法来处理内存中的数据集合。
基本定义
List<T> 是 .NET 中的一个泛型集合类,表示一个强类型对象列表。它提供了搜索、排序和操作列表的方法。
与数组不同,List 可以根据需要动态地增长和缩小。与传统数组相比,它们为大多数操作提供了更好的性能。
List 属于 System.Collections.Generic 命名空间。它实现了IList<T>、ICollection<T> 和 IEnumerable<T> 等多个接口。
ASP.NET List 示例
以下示例演示了如何在 ASP.NET Web API 控制器中使用 List<T> 来管理产品集合。
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.MapControllers(); app.Run();
这设置了一个基本的 ASP.NET 应用程序,并支持控制器。MapControllers 方法为控制器启用属性路由。
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List<Product> _products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99m },
new Product { Id = 2, Name = "Mouse", Price = 19.99m },
new Product { Id = 3, Name = "Keyboard", Price = 49.99m }
};
[HttpGet]
public ActionResult<List<Product>> GetAllProducts()
{
return _products;
}
[HttpPost]
public ActionResult<Product> AddProduct([FromBody] Product product)
{
product.Id = _products.Max(p => p.Id) + 1;
_products.Add(product);
return CreatedAtAction(nameof(GetProductById),
new { id = product.Id }, product);
}
[HttpGet("{id}")]
public ActionResult<Product> GetProductById(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
return product;
}
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, [FromBody] Product product)
{
var existingProduct = _products.FirstOrDefault(p => p.Id == id);
if (existingProduct == null) return NotFound();
existingProduct.Name = product.Name;
existingProduct.Price = product.Price;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
_products.Remove(product);
return NoContent();
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
此控制器使用 List<Product> 作为内存数据存储来演示 CRUD 操作。该列表已初始化为三个示例产品。
GetAllProducts 方法返回整个列表。AddProduct 向列表添加一个新产品并为其分配一个新 ID。GetProductById 使用 LINQ 的 FirstOrDefault 按 ID 查找产品。
UpdateProduct 修改列表中的现有产品。DeleteProduct 从列表中删除产品。所有方法均返回适当的 HTTP 状态码。
该示例展示了如何将 List<T> 用作简单的内存数据库以供演示。在实际应用程序中,您通常会使用合适的数据库。
来源
在本文中,我们探讨了 ASP.NET 8 中的 List<T> 集合。这个多功能类对于在 .NET 应用程序中处理对象集合至关重要。