【问题标题】:Collection Creation/Design Question集合创建/设计问题
【发布时间】:2011-08-29 18:06:34
【问题描述】:

我需要根据用户选择的报告类型将集合绑定到 GridView。

每个报告略有不同,但使用相同的基本结果集,其中包含许多列。在绑定之前,我想遍历结果集并复制到一个更简单的集合(3 个字符串变量,分别称为“column1”、“column2”、“column3”)。

代码:

namespace etc.etc.etc
{
    public class ReportEntity
    {
        public string column1 { get; set; }

        public string column2 { get; set; }

        public string column3 { get; set; }
    }
}

List<ReportEntity> a = new List<ReportEntity>();
ReportEntity[] b = new ReportEntity[results.Length];
for (int i = 0; i < results.Length; i++)
{
    //a[i].column1 = results[i].class.desc;
    //a[i].column2 = results[i].student.firstname;
    //a[i].column3 = results[i].timescanned.ToString();

    //b[i].column1 = results[i].class.desc;
    //b[i].column2 = results[i].student.firstname;
    //b[i].column3 = results[i].timescanned.ToString();
}

取消注释我为a 设置值的位置会得到Index was out of range. Must be non-negative and less than the size of the collection.。 取消注释我为b 设置值的位置会给出Object reference not set to an instance of an object.

results肯定有很多记录。我可能做错了什么?

【问题讨论】:

    标签: c# collections


    【解决方案1】:
    • 您在第一种情况下得到IndexOutRangeException,因为您刚刚创建了一个列表实例,但该列表不包含任何元素。

    • 您在第二种情况下得到NullReferenceException,因为您刚刚用results.Lengthnulls 填充数组。

    你应该做的是显式创建ReportEntity的实例并放入底层数据结构。

    List<ReportEntity> a = new List<ReportEntity>();
    ReportEntity[] b = new ReportEntity[results.Length];
    for (int i = 0; i < results.Length; i++)
    {
        a.Add(new ReportEntity() {column1 = results[i].class.desc,
                                  column2 = results[i].student.firstname,
                                  column3 =  results[i].student.firstname  }
    
        b[i] = new ReportEntity() {column1 = results[i].class.desc,
                                  column2 = results[i].student.firstname,
                                  column3 =  results[i].student.firstname  }
    }
    

    或者您可以使用Select 扩展方法进行LINQ,以喜欢另一个答案中提到的内容。

    【讨论】:

      【解决方案2】:

      要向列表添加值,请使用Add 方法。

      或者,使用 LINQ 中的选择:

      var a = results.Select(r => new ReportEntity { 
        column1 = r.class.desc,
        column2 = r.student.firstname,
        column3 = r.timescanned.ToString()
      }).ToList();
      

      【讨论】:

      • 哦,是的。但是那我需要那个实体类的构造函数
      • 上面的语法不需要任何其他构造函数,而不是默认的
      猜你喜欢
      • 2019-12-11
      • 2021-04-27
      • 2015-09-12
      • 2013-10-20
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多