Is there an elegant way of converting this string array:
string[] a = new[] {\"name\", \"Fred\", \"colour\", \"green\", \"sport\", \"tennis\"};
public static IEnumerable EveryOther(this IEnumerable source)
{
bool shouldReturn = true;
foreach (T item in source)
{
if (shouldReturn)
yield return item;
shouldReturn = !shouldReturn;
}
}
public static Dictionary MakeDictionary(IEnumerable source)
{
return source.EveryOther()
.Zip(source.Skip(1).EveryOther(), (a, b) => new { Key = a, Value = b })
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
The way this is set up, and because of the way Zip
works, if there are an odd number of items in the list the last item will be ignored, rather than generation some sort of exception.
Note: derived from this answer.