tags:

views:

76

answers:

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
+1  A: 

Something like:

parts[parts.length -1]

should do the trick.

codykrieger
Ok, but if length is ever 0, this will crash...
Steven Sudit
@Steven Sudit - True, but you can just put in a check: parts.length > 0 ? parts[parts.length - 1] : ""
James Black
True, good call on that one.
codykrieger
@James: That looks like a good fix.
Steven Sudit
+1  A: 
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
James Black
A: 

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]};
AllenG
+7  A: 
from line in File.ReadAllLines(path)
select line.Split('|').LastOrDefault()
Jacob
+1 - OK, this looks like a great answer. I have never used this function.
James Black
Nice answer Jacob
Gopi