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

5
  • Is linq is necessary and what would be output? Commented Apr 14, 2014 at 6:40
  • 1
    Why not use String.Split?stackoverflow.com/questions/70405/… Commented Apr 14, 2014 at 6:40
  • I'd rather parse this input string using a state-machine, it would be a lot faster and consume less memory. Commented Apr 14, 2014 at 6:40
  • 3
    Without LINQ, you can use String.Split() method like String.Split(new char[] {'|', ';'}, StringSplitOptions.RemoveEmptyEntries); Commented Apr 14, 2014 at 6:43
  • String.Split is more than enough for simple cases. Regex can cover most advanced cases. LINQ should be used to handle the output of splitting/parsing, not perform the parsing itself Commented Apr 14, 2014 at 6:48

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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));

Comments

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);

2 Comments

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.
Why not just use string.Join again instead of foreach?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.