0

I have a string like this, which is dynamic and can be any length from 1 to 1000 parts in the format of id^part~:

string Parts = "1^PartOne~2^PartTwo~3^Part3~4^PartFour"

Is it possible to convert this into an iList of strings like the following using LINQ?

PartOne
PartTwo
PartThree
PartFour

or do I just need to split twice and add to a list manually?

1
  • 2
    What did you try yourself? Commented Aug 5, 2014 at 9:35

4 Answers 4

4

Why not using regular string.Split and Select?

var list = Parts.Split('~').Select(x => x.Split('^')[1]);

You can do a .ToList() to make it a IList in the end, as requested.

It splits the various elements (1^PartOne), and then splits them again to take the last part (PartOne)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Started to doubt myself.
2

Personally, I'd prefer a Dictionary<string, string> over a List<string> since you can represent both key and value:

string parts = "1^PartOne~2^PartTwo~3^Part3~4^PartFour";

var dict = parts.Split(new[] { '~' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(part => part.Split('^'))
                .ToDictionary(split => split[0], split => split[1]);

Comments

1

Here's another method:

int n = 0;
var result = Parts
    .Split(new char[] {'^','~'}, StringSplitOptions.None)
    .Where(x => !int.TryParse(x,out n));

Since this is a regular sequence of the form "number^text~", we use Split to split on the special characters and filter out the purely numeric parts to get the text required.

Demo

Comments

-1

You can use this code. It is working as your requirement. Must try it.

C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singh
{
    class Program
    {
        static void Main(string[] args)
        {
            string Parts = "1^PartOne~2^PartTwo~3^PartThree~4^PartFour";
            string[] data = new string[5];
            data = Parts.Split('^', '~');


            for (int i = 0; i < data.Count(); i++)
            {
                i++;
                string names = data[i];
                Console.WriteLine(names.ToString());
            }
            Console.ReadLine();
        }
    }
}

Result:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.