Linq to FileHelpers Class

I am trying to get the results of a linq query int a file. I created and array of the same type as the FileHelpers class I created, then queried the data and assigned the values to the array I just created.

I get the following error:

Object reference not set to an instance of an object.

The strange thing is that the item giving out the error is the one that is getting a value assigned to it. Not sure why this is happening:

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);

including product class:

[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;


}  

Answers


You must initialize items[i] before using it in the for loop. The problem is that you have created the array, but its individual elements are null. I guess you'd want to assign the return of your linq query to this array, after doing some projection using Select().

Though I don't know the specifics of your class, I suppose you'd do it on the following lines:

producdt[] items = (from d in dbContext.Products
                   select new producdt(){ 
                                          Field1 = d.Field1, 
                                          Field2 = d.Field2, 
                                          Field3 = d.Field3, 
                                          Field4 = d.Field4
                                         }).ToArray();

Need Your Help

Consume a wcf duplex service in console application

wcf wcf-binding duplex pollingduplexhttpbinding

I have a wcf duplex service with work fine in silverlight. but the same service I want to consume in windows console application. My code as follow:

How to get android battery level from ubuntu?

android linux ubuntu batterylevel

I'm trying to access the battery life of my android phone (Samsung Galaxy Y S5360) from my pc (im running ubuntu 14.04), but i can't find anything relevant and so i was wondering if there are any

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.