0

With the code below, on the foreach, I get an exception.

I place breakpoint on the csv (second line), I expand the result, I see 2 entries thats ok.

When I do the same on the csv in the foreach, I get an excpetion : can't read from closed text reader.

Any idea ?

Thanks,

My CSV file :

A0;A1;A2;A3;A4 B0;B1;B2;B3;B4 

The code

var lines = File.ReadLines("filecsv").Select(a => a.Split(';')); IEnumerable<IEnumerable<MyClass>> csv = from line in lines select (from piece in line select new MyClass { Field0 = piece[0].ToString(), Field1 = piece[1].ToString() } ).AsEnumerable<MyClass>(); foreach (MyClass myClass in csv) Console.WriteLine(myClass.Field0); Console.ReadLine(); 

MyClass :

public class MyClass { public string Field0 { get; set; } public string Field1 { get; set; } } 

3 Answers 3

2

Perhaps something like this instead, will give you exactly what you want:

var jobs = File.ReadLines("filecsv") .Select(line => line.Split(',')) .Select(tokens => new MyClass { Field0 = tokens[0], Field1 = tokens[1] }) .ToList(); 

The problem you have is that you're saving the Enumerable, which has delayed execution. You're then looking at it through the debugger, which loops through the file, does all the work and disposes of it. Then you try and do it again.

The above code achieves what you currently want, is somewhat cleaner, and forces conversion to a list so the lazy behaviour is gone.

Note also that I can't see how your from piece in line could work correctly as it currently stands.

Sign up to request clarification or add additional context in comments.

Comments

0

Perhabs it is because LINQ does not directly read all the items, it just creates the connection it read if it is needed.

You could try to cast:

var lines = File.ReadLines("filecsv").Select(a => a.Split(';')).ToArray(); 

Comments

0

I suspect it is a combination of the yield keyword (used in Select()) and the internal text reader (in ReadLines) not "agreeing".

Changes the lines variable to var lines = File.ReadLines("filecsv").Select(a => a.Split(';')).ToArray();

That should sort it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.