String for KeyValuePair using LINQ

2

I'm getting a string in the format "N1N2S3S4L5L6O7O8X" and needs to be passed to a KeyValuePair or 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?

    
asked by anonymous 26.06.2017 / 16:12

2 answers

2

Using LINQ in this type of task will only make the code difficult to read.

Using a for normal seems 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 in .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;       
    }
}
    
26.06.2017 / 16:55
2

Using linq 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 at .NetFiddle

    
26.06.2017 / 16:51