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;
}
}