集合创建/设计问题
我需要根据用户选择的报表类型将集合绑定到 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 超出范围。必须为非负数且小于集合的大小。
。 取消注释我为 b
设置值的位置会导致 未将对象引用设置为对象的实例。
。
results
肯定有很多记录。我可能做错了什么?
I need to be binding a collection to a GridView depending on the report type selected by the user.
Each report varies slightly but uses the same basic result set which has many columns. Before I bind I want to loop through the result set and copy to a simpler collection (3 string variables called 'column1', 'column2', 'column3').
Code:
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();
}
Uncommenting where I set values for a
gives Index was out of range. Must be non-negative and less than the size of the collection.
.
Uncommenting where i set values for b
gives Object reference not set to an instance of an object.
.
results
definitely has many records. What could I be doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一种情况下,您会得到
IndexOutRangeException
,因为您刚刚创建了列表的实例,但此列表不包含任何元素。在第二种情况下,您会得到
NullReferenceException
,因为您刚刚用results.Length
填充了数组nulls
。您应该做的是显式创建
ReportEntity
实例并放入底层数据结构。或者,您可以使用
Select
扩展方法进行 LINQ,以像另一个答案中提到的那样。You get
IndexOutRangeException
in the 1st case because you just created an instance of list but this list doesn't contain any elements.You get
NullReferenceException
in the 2nd case because you just filled array withresults.Length
ofnulls
.What you should do is to explicitly create instance of
ReportEntity
and put in the underlying data structure.Or you can you LINQ with
Select
extenssion method to like it's mentioned in another answer.要向列表添加值,请使用
Add
方法。或者,使用 LINQ 中的选择:
To add value to a List use the
Add
method.Alternatively, use the select from LINQ: