String for Keyvaluepair using LINQ

Asked

Viewed 246 times

2

I am receiving a string in the format "N1N2S3S4L5L6O7O8X" and I need it passed to a KeyValuePair or for a NameValueCollection.

Where the key is the letter and the number the value.

{ N, 1 }
{ N, 2 }
{ S, 3 }

How to do this using LINQ?

2 answers

2

Using the Formula you can use this way:

var texto = "N1N2S3S4L5L6O7O8X"; 
var keys = texto.Zip(texto.Skip(1), (Key, Value) => new {Key, Value}).
            Where((pair, index) => index % 2 == 0)
            .Select(k => new KeyValuePair<string, string>(k.Key.ToString(), k.Value.ToString())); 

See working on .Netfiddle

2


Using LINQ for this type of task will only make the code hard to read.

Use a for normal seems to me a much better idea.

var lista = new List<KeyValuePair<char, char>>();

for(int i = 0; i < str.Length - 1; i += 2)
{
    lista.Add(new KeyValuePair<char, char>(str[i], str[i + 1]));
}

If you want to insist on LINQ, you can use the method Zip

var lista = str.Zip(str.Skip(1), (k, v) => new KeyValuePair<char, char>(k, v))
               .Where((pair, index) => index % 2 == 0);

Full example (see working on . NET Fiddle)

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

public class Program
{
    public static void Main()
    {
        var str = "N1N2S3S4L5L6O7O8X";

        var lista = SemLinq(str);       

        foreach (var kvp in lista)
        {
            Console.WriteLine($"Key: {kvp.Key} Value: {kvp.Value}");
        }

        var lista2 = ComLinq(str);

        foreach (var kvp in lista)
        {
            Console.WriteLine($"Key: {kvp.Key} Value: {kvp.Value}");
        }
    }

    public static List<KeyValuePair<char, char>> ComLinq(string str)
    {
        var lista = str.Zip(str.Skip(1), (k, v) => new KeyValuePair<char, char>(k, v)).Where((pair, index) => index % 2 == 0);

        foreach (var kvp in lista)
        {
            Console.WriteLine($"Key: {kvp.Key} Value: {kvp.Value}");
        }

        return lista.ToList();
    }

    public static List<KeyValuePair<char, char>> SemLinq(string str)
    {
        var lista = new List<KeyValuePair<char, char>>();

        for(int i = 0; i < str.Length - 1; i += 2)
        {
            lista.Add(new KeyValuePair<char, char>(str[i], str[i + 1]));
        }

        return lista;       
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.