Rob
Rob

Reputation: 13

LINQ from string array

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?

Upvotes: 0

Views: 83

Answers (4)

Kalu Singh Rao
Kalu Singh Rao

Reputation: 1697

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

Upvotes: -1

shree.pat18
shree.pat18

Reputation: 21757

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

Upvotes: 1

DGibbs
DGibbs

Reputation: 14618

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

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 157146

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)

Upvotes: 4

Related Questions