Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in C#?

Tags:

c#

I am trying to parse the following string and get the result.

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6"

I am trying to get the following result after the split.

string SiteA = "Pages:1,Documents:6"
string SiteB = "Pages:4"

Here is my code but it doesn't seem to be working. How can I get all related "SiteA" and "SiteB"?

List<string> listItem = new List<string>();
string[] keyPairs = test.Split(',');
string[] item;
foreach (string keyPair in keyPairs)
{
    item = keyPair.Split(':');
    listItem.Add(string.Format("{0}:{1}", item[0].Trim(), item[1].Trim()));
}
like image 534
nav100 Avatar asked Aug 14 '26 12:08

nav100


2 Answers

I would use a Lookup for this:

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";
var listItemsBySite = test.Split(',')
                          .Select(x => x.Split(':'))
                          .ToLookup(x => x[0], 
                                    x => string.Format("{0}:{1}", 
                                                       x[1].Trim(), 
                                                       x[2].Trim()));

You can then use it like this:

foreach (string item in listItemsBySite["SiteA"])
{
    Console.WriteLine(item);
}
like image 100
BrokenGlass Avatar answered Aug 17 '26 02:08

BrokenGlass


Here's my solution... pretty elegant in LINQ, you can use anonymous objects, Tuples, KeyValuePair, or your own custom class. I'm just using an anonymous type.

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";

            var results = test
                .Split(',')
                .Select(item => item.Split(':'))
                .ToLookup(s => s[0], s => new { Key = s[1], Value = s[2] });

            // This code just for display purposes
            foreach (var site in results)
            {
                Console.WriteLine("Site: " + site.Key);

                foreach (var value in site)
                {
                    Console.WriteLine("\tKey: " + value.Key + " Value: " + value.Value);
                }
            }
like image 41
James Michael Hare Avatar answered Aug 17 '26 01:08

James Michael Hare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!