Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 收藏创作/设计问题_C#_Collections - Fatal编程技术网

C# 收藏创作/设计问题

C# 收藏创作/设计问题,c#,collections,C#,Collections,我需要根据用户选择的报表类型将集合绑定到GridView 每个报告略有不同,但使用相同的基本结果集,该结果集有许多列。在绑定之前,我想循环遍历结果集并复制到一个更简单的集合(3个名为“column1”、“column2”、“column3”的字符串变量) 代码: 名称空间等 { 公共类报表实体 { 公共字符串column1{get;set;} 公共字符串column2{get;set;} 公共字符串column3{get;set;} } } 列表a=新列表(); ReportEntity[]b=

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

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

代码:

名称空间等
{
公共类报表实体
{
公共字符串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();
  • 在第一种情况下,您会得到
    IndexOutRangeException
    ,因为您刚刚创建了list的一个实例,但该列表不包含任何元素

  • 在第二种情况下,您会得到
    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  }
}