If I have a IDictionary<int, int>, is it possible to receive a IEnumerable<int>, which
would contain every KeyValuePair<int, int> disassembled into two (int, int) entries inserted one after another?
Small example:
Dictionary:
5 - 25
6 - 36
7 - 49
Wanted Enumerable:
5, 25, 6, 36, 7, 49
Also, I wanted to have this in one super-pretty statement, but I couldn't think of an appropriate one :)
Update:
Does LINQ allow to insert more than one element per .Select statement, something sharing the idea of:
xyz.Select(t => (t, null))
so that the resulting Enumerable would contain both t and null right after it?
You could use SelectMany<TSource, TResult>(IEnumerable<TSource>, Func<TSource, IEnumerable<TResult>>) (plus overloads). Here's an example
var dict = new Dictionary<int, int> {
{ 5, 25 },
{ 6, 36 },
{ 7, 49 }
};
var projection = dict.SelectMany(kv => new[] { kv.Key, kv.Value });
As per the comments, this is just one way of achieving what you have asked.
You could create a method that will decompose your dictionary into an IEnumerable in the way you want.
using System.Collections.Generic;
using System;
public class C {
public static void Main()
{
var dic = new Dictionary<int,int>();
dic[0] = 1;
dic[2] = 3;
dic[4] = 5;
foreach (var i in Decompose(dic))
Console.WriteLine(i);
Console.ReadLine();
}
public static IEnumerable<int> Decompose(IDictionary<int,int> dic)
{
foreach (var i in dic.Keys)
{
yield return i;
yield return dic[i];
}
}
}
Output:
0
1
2
3
4
5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With