4

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

2 Answers 2

3

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.

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

2 Comments

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.
I agree, I just didn't want to get too far from the original code.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.