4

I am processing CSV File

Say

ABC|06|001
PPP|06|001

I am running LINQ to split the CSV

var path = Server.MapPath("~/App_Data/CSV.txt");
var _collectCSGData = from line in File.ReadAllLines(path)
                      let parts = line.Split('|')
                       select new { ID = parts[0],Assignment=parts[1]};

How to get the last item of each line ?

(i.e)

001
001
2
  • This looks more like pipe-delimited text, not CSV. Commented Aug 12, 2010 at 17:47
  • @Stephen Cleary - If it is delimited by columns then it seems people just call it CSV, regardless ofthe delimiter, as it is something that can be imported into Excel easily. Commented Aug 12, 2010 at 17:51

4 Answers 4

8
from line in File.ReadAllLines(path)
select line.Split('|').LastOrDefault()
Sign up to request clarification or add additional context in comments.

1 Comment

+1 - OK, this looks like a great answer. I have never used this function.
1

Something like:

parts[parts.length -1]

should do the trick.

1 Comment

@Steven Sudit - True, but you can just put in a check: parts.length > 0 ? parts[parts.length - 1] : ""
1
var _collectCSGData = from line in File.ReadAllLines(path) 
                      let parts = line.Split('|') 
                      let assignment = parts[parts.length - 1]
                       select assignment;

This should work, if you need to massage data, let is your friend.

UPDATE:

Since parts may be empty you can have:

let assignment = parts.length > 0 ? parts[parts.length - 1] : String.Empty

Comments

0

If you know it's the third part, how about adding to your anonymous constructor:

var _collectCSGData = from line in File.ReadAllLines(path)
                      let parts = line.Split('|');
                      select new 
                         {ID = parts[0], Assignment = parts[1], Data = parts[2]};

Or, if it's just "The last Item no matter how many items"

var _collectCSGData = from line in File.ReadAllLines(path)
                      let parts = line.Split('|');
                      select new 
                        {ID = parts[0], Assignment = parts[1], Data = parts[part.length-1]};

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.