0

我正在尝试在文件中获取 linq 查询的结果。我创建了与我创建的 FileHelpers 类相同类型的数组,然后查询数据并将值分配给我刚刚创建的数组。

我收到以下错误:

Object reference not set to an instance of an object.

奇怪的是,发出错误的项目是获得分配给它的值的项目。不知道为什么会这样:

NorthwindEntities dbContext = new NorthwindEntities();
        var q = from d in dbContext.Products
                select d;
        producdt[] items = new producdt[q.Count()];

        for (int i = 0; i < q .Count(); i++)
        {
            items[i].Field1 = q.ToList()[i].ProductName;
        }
        FileHelperEngine<producdt> engine = new FileHelperEngine<producdt>();
            engine.WriteFile("test.text", items);

包括产品类别:

[FixedLengthRecord(FixedMode.ExactLength)]
public sealed class producdt
{

[FieldFixedLength(10)]
public String Field1;

[FieldFixedLength(10)]
public String Field2;

[FieldFixedLength(10)]
public String Field3;

[FieldFixedLength(10)]
public String Field4;

[FieldFixedLength(10)]
public String Field5;


}  
4

1 回答 1

4

items[i]您必须在for循环中使用它之前进行初始化。问题是您已经创建了数组,但它的各个元素是null. 我猜你想在使用Select().

虽然我不知道你班级的具体情况,但我想你会按照以下几行来做:

producdt[] items = (from d in dbContext.Products
                   select new producdt(){ 
                                          Field1 = d.Field1, 
                                          Field2 = d.Field2, 
                                          Field3 = d.Field3, 
                                          Field4 = d.Field4
                                         }).ToArray();
于 2013-05-01T16:28:55.727 回答