String Split ASP.NET/C#

I am processing a CSV file

Let's say

ABC|06|001 PPP|06|001 

I run LINQ to split 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 element of each row?

(those.)

 001 001 
+4
source share
4 answers
 from line in File.ReadAllLines(path) select line.Split('|').LastOrDefault() 
+8
source

Sort of:

 parts[parts.length -1] 

gotta do the trick.

+1
source
 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 the data, let is your friend.

UPDATE:

Since the parts may be empty, you can:

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

If you know this 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 “Last item regardless of the number of 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]}; 
0
source

All Articles