开发者

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 ?

(i.e)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜