简体   繁体   中英

String Split ASP.NET /C#

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 ?

(ie)

001
001
from line in File.ReadAllLines(path)
select line.Split('|').LastOrDefault()

Something like:

parts[parts.length -1]

should do the trick.

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

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]};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM