7

I am using a string to store country code with its cost centre code value . I want to spilit it out the string using LINQ query by | and ; characters. The srting is

IND|001;TWN|002;USA|003;LDN|;MYS|005;

Please help me to spilt out the string value using LINQ

Suryakavitha
  • 1,371
  • 5
  • 33
  • 49

4 Answers4

10

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
DarkWanderer
  • 8,739
  • 1
  • 25
  • 56
2

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);
Muhammad Umar
  • 3,761
  • 1
  • 24
  • 36
0

You can use this:

string temp= "IND|001;TWN|002;USA|003;LDN|;MYS|005";
IEnumerable<string> returnList = temp.Split(';')
    .Where(g=>!String.IsNullOrEmpty(g))
    .Select(c => c.Substring(0, c.IndexOf('|')) + c.Substring(c.IndexOf('|') + 1));
zellus
  • 9,617
  • 5
  • 39
  • 56
0
var myString = "IND|001;TWN|002;USA|003;LDN|;MYS|005;";
            var result = from sp in myString.Split(';')
                         let spr = sp.Split('|')
                         select string.Join(" ", spr);
            string append = string.Empty;
            foreach (var item in result)
            {
                append += item + "\n";
            }
            Console.WriteLine(append);
tl simo
  • 1
  • 1
  • 1
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained. – Amit Verma Feb 05 '21 at 11:14
  • Why not just use `string.Join` again instead of `foreach`? – General Grievance Feb 05 '21 at 15:04