You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用EF Core从数据库填充多维数组出现索引越界如何解决

问题原因

  • 错误1:尝试1的循环中每次都重新实例化二维数组,覆盖上一次的赋值,最终返回的数组永远只有1行(最后一次循环的行数据),访问下标[1,x]自然触发索引越界。
  • 错误2:OrderByDescending是延迟执行方法,你没有将排序后的结果赋值给变量,排序逻辑完全没有生效。
  • 错误3:分7次单独查询各个列的列表,若某行对应字段为null,会导致不同列表的长度不一致,遍历取[i]时可能出现越界,且多次查询数据库性能损耗很大。
  • 错误4:尝试3中_context.ArticlesList.ToList()返回的是List<ArticlesList>类型,你声明的返回值是List<object>,控制器接收后无法直接访问ArticlesList的属性,触发类型转换错误。

最优解决方案(推荐,无需使用二维数组)

直接返回强类型的文章列表,比数组更易维护,也不会出现索引对应错误:

数据查询代码

public class GetArticlesCardDetails
{
    private static readonly ApplicationDbContext _context = new();
    public static List<ArticlesList> GetCardDetails()
    {
        _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        // 直接查询排序后的所有文章
        return _context.ArticlesList
            .OrderByDescending(x => x.PostedDateTime)
            .ToList();
    }
}

控制器赋值代码

var articles = GetArticlesCardDetails.GetCardDetails();
var viewModel = new ArticlesViewModel
{
    // 做非空判断避免没有数据时报错
    Article1CardImage = articles.Count >= 1 ? articles[0].TitleImageUrl : string.Empty,
    Article1CardTitle = articles.Count >= 1 ? articles[0].Title : string.Empty,
    Article1CardContent = articles.Count >= 1 ? articles[0].Snippet : string.Empty,
    Article1CardDate = articles.Count >= 1 && articles[0].PostedDateTime.HasValue 
        ? articles[0].PostedDateTime.Value.ToString("yyyy-MM-dd") 
        : string.Empty,

    Article2CardTitle = articles.Count >= 2 ? articles[1].Title : string.Empty,
    Article2CardContent = articles.Count >= 2 ? articles[1].Snippet : string.Empty,
    Article2CardDate = articles.Count >= 2 && articles[1].PostedDateTime.HasValue 
        ? articles[1].PostedDateTime.Value.ToString("yyyy-MM-dd") 
        : string.Empty
};

若必须使用二维数组的正确写法

public class GetArticlesCardDetails
{
    private static readonly ApplicationDbContext _context = new();
    public static string[,] GetCardDetails()
    {
        _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        // 一次性查询所有排序后的文章
        var articlesList = _context.ArticlesList
            .OrderByDescending(x => x.PostedDateTime)
            .ToList();
        int rowCount = articlesList.Count;
        // 提前初始化固定大小的二维数组:行数*7列
        string[,] articles = new string[rowCount, 7];
        
        for (int i = 0; i < rowCount; i++)
        {
            var item = articlesList[i];
            articles[i, 0] = item.ArticleReference;
            articles[i, 1] = item.TitleImageUrl;
            articles[i, 2] = item.UserId;
            articles[i, 3] = item.Title;
            articles[i, 4] = item.Snippet;
            articles[i, 5] = item.PostedDateTime?.ToString() ?? string.Empty;
            articles[i, 6] = item.WeeklyNewsList.ToString();
        }
        return articles;
    }
}

内容的提问来源于stack exchange,提问作者DMur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:06:03