How to split a string using LINQ

I am assuming you need a list of Tuple<string,string> as output.

var myString = "IND|001;TWN|002;USA|003;LDN|;MYS|005;";
var objects = myString.Split(';')
        .Where(x => !string.IsNullOrEmpty(x))
        .Select (x => x.Split('|'))
        .Select (x => Tuple.Create(x[0],x[1]))
        .ToList();

Result:

IND 001 
TWN 002 
USA 003 
LDN
MYS 005

Rather then LINQ use String.Split.

string s = "IND|001;TWN|002;USA|003;LDN|;MYS|005;";

string[] splitData = s.Split(new string[] { "|", ";" }, StringSplitOptions.RemoveEmptyEntries);

Tags:

C#

Linq