tags:

views:

85

answers:

2

Given the code below:

            var query = from line in ClientCount()
                    let aLine = line.Split(",")
                    where aLine.GetValue(1) != 0
                    select aLine;

To query a csv file, will aLine.GetValue(1) get the 1st line (after 0) in the .csv file, or 1st string, eg:

abc, def

And therefore get def? I want to get def, but then I also want to pick up, title2 above that in a file like so:

title, title2

abc, def

How can I do this?

BTW I know there is LINQ To CSV for this but I am doing this myself for the practise.

Thanks

+1  A: 

So, if I read this correctly you want to get the pair "title2","def"; or otherwise put, you want to get the values of column1. The only change you need to your LINQ is as follows:

var query = from line in ClientCount()
    let aLine = line.Split(new[] { ',' })
    where aLine.GetValue(1) != "0"
    select aLine.GetValue(1);

This would exclude rows where the value of the second column is "0", which is what I'm assuming you were attempting to do. This code compiles and runs and gives an IEnumerable with values of "def" and "title2" for the set you specified.

Payton Byrd
I would have done `line.Split(',')` and `aLine[1]`. Less typing is less typing, and the added characters don't provide any benefits in functionality or legibility.
Joel Mueller
I agree, I just didn't want to get too far from the original code.
Payton Byrd
My original post had bad formatting. See now.
dotnetdev
+1  A: 

While practice is all well and good, CSV is actually a lot more complex than the name suggests - you have quoted/unquoted, multi-line, and the horrible issue where in some areas the "c" becomes a period (".").

I strongly recommend you use something pre-rolled, such as CsvReader.

(Fortunately TSV isn't usually nearly so nasty)

Marc Gravell
+1 for identifying "simple" CSV is really not simple at all.
CrimsonX