Pikachu620
Pikachu620

Reputation: 483

IEnumerable array disappeared in Visual C#

I declared a IEnumerable array

IEnumerable<DataRow>[] drs=new IEnumerable<DataRow>[5];

and populated it by

for(int i=0;i<5;i++)
{
    drs[i]=
        from x in dt.AsEnumerable()                 //dt is a DataTable
        where x["ID"].ToString() == i.ToString()    //Assuming dt has a column named ID
        select x;
}

When I get out of the scope of the for loop, the data I populated are all gone. Why is this?

Upvotes: 0

Views: 135

Answers (1)

Peter Aylett
Peter Aylett

Reputation: 780

Linq expressions are lazy evaluated. That means that C# doesn't actually access the record set in the code above. Rather, it just keeps track of an expression that will access the data some later time.

In the case of collection of DataRows this can cause problem because 'later' might mean after the database connection (or at least the resultset) is closed.

Fix this by forcing Linq to evaluate the enumerables at the time, for example by calling ToList().

for(int i=0;i<5;i++)
{
    drs[i]=
        (from x in dt.AsEnumerable()                 //dt is a DataTable
        where x["ID"].ToString() == i.ToString()    //Assuming dt has a column named ID
        select x).ToList();
}

Upvotes: 2

Related Questions