简体   繁体   中英

How to convert Comma separated string to KeyValuePair of LIST or IEnumerable

I have a dynamic string:

It looks like "1: Name, 2: Another Name" this. I want to split it and convert it to a List<KeyValuePair<int, string>> or IEnmerable<KeyValuePair<int, string>>

I tried this.

myString.Split(',').Select(s => s => new KeyValuePair<int, string>( Convert.ToInt32(s.Substring(s.LastIndexOf(':'), s.Substring(0, s.LastIndexOf(':')) + 1))))

Does not to help much. I can do strings of Dictionary or a foreach or a for loop. I rather do it as a key value pair lambda expression one liner.

You need to split twice first by comma, then by colon. Try this code:

var input = "1: Name, 2: Another Name";

var list = input.Split(',')
    .Select(p =>
    {
        var kv = p.Split(':');
        return new KeyValuePair<int, string>(int.Parse(kv[0].Trim()), kv[1]);
    })
    .ToList();

Try this:

myString.Split(',').Select(s => new KeyValuePair<int, string>(
   int.Parse(s.Split(':').GetValue(0).ToString()),
   s.Split(':').GetValue(1).ToString()
));

One-liner:

WARNING: No exception handling

myString.Split(',').Select(x => new KeyValuePair<int, string>(int.Parse(x.Split(':')[0]), x.Split(':')[1]))

Another way to achieve that with the beauty of regex:

var result = new List<KeyValuePair<int, string>>();
foreach (Match match in Regex.Matches("1: Name, 2: Another Name", @"((\d+): ([\w ]+))"))
{
    result.Add(new KeyValuePair<int, string>(int.Parse(match.Groups[2].Value), match.Groups[3].Value));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM