C# 收藏创作/设计问题
我需要根据用户选择的报表类型将集合绑定到GridView 每个报告略有不同,但使用相同的基本结果集,该结果集有许多列。在绑定之前,我想循环遍历结果集并复制到一个更简单的集合(3个名为“column1”、“column2”、“column3”的字符串变量) 代码:C# 收藏创作/设计问题,c#,collections,C#,Collections,我需要根据用户选择的报表类型将集合绑定到GridView 每个报告略有不同,但使用相同的基本结果集,该结果集有许多列。在绑定之前,我想循环遍历结果集并复制到一个更简单的集合(3个名为“column1”、“column2”、“column3”的字符串变量) 代码: 名称空间等 { 公共类报表实体 { 公共字符串column1{get;set;} 公共字符串column2{get;set;} 公共字符串column3{get;set;} } } 列表a=新列表(); ReportEntity[]b=
名称空间等
{
公共类报表实体
{
公共字符串column1{get;set;}
公共字符串column2{get;set;}
公共字符串column3{get;set;}
}
}
列表a=新列表();
ReportEntity[]b=新的ReportEntity[results.Length];
for(int i=0;i
取消注释我为a
设置的值时给出的索引超出范围。必须为非负数且小于集合的大小。
。
在为b
设置值的地方取消注释会使对象引用未设置为对象的实例。
结果
肯定有很多记录。我可能做错了什么?要向列表添加值,请使用add
方法
或者,使用select from LINQ:
var a = results.Select(r => new ReportEntity {
column1 = r.class.desc,
column2 = r.student.firstname,
column3 = r.timescanned.ToString()
}).ToList();
- 在第一种情况下,您会得到
,因为您刚刚创建了list的一个实例,但该列表不包含任何元素IndexOutRangeException
- 在第二种情况下,您会得到
,因为您刚刚用NullReferenceException
结果填充了数组
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 }
}
List a=新列表();
ReportEntity[]b=新的ReportEntity[results.Length];
for(int i=0;i
或者你可以用
选择扩展方法来选择另一个答案中提到的方法。哦,是的。但是我需要在实体类上使用构造函数吗?上述语法不需要默认构造函数以外的任何其他构造函数
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 }
}