I have one
Dictionary<string, List<string>> demo = new Dictionary<string, List<string>>();
List<String> key1val= new List<string>();
key1val.Add("1");
key1val.Add("2");
key1val.Add("3");
List<String> key2val= new List<string>();
key2val.Add("4");
key2val.Add("5");
demo.Add("key1", key1val);
demo.Add("key2", key2val);
foreach (var item in demo)
{
foreach(var it in item.Value)
{
Console.WriteLine(it);
}
}
I want to iterate though all keys like key1,key2
.
if current item is key1
then inside loop should take all values with respect to key1
and iterate it into 2nd loop
loop
iterate though key1
iterate though [1,2,3]
loop
iterate though key2
iterate though [4,5]
Well, use 2 nested loops.
The outer one iterating over the keys, the inner one over the values of the corresponding entry :
Dictionary<string, List<string>> demo = new Dictionary<string, List<string>>();
List<String> key1val= new List<string>();
key1val.Add("1");
key1val.Add("2");
key1val.Add("3");
List<String> key2val= new List<string>();
key2val.Add("4");
key2val.Add("5");
demo.Add("key1", key1val);
demo.Add("key2", key2val);
foreach (var key in demo.Keys)
{
Console.WriteLine(key);
foreach (var elem in demo[key])
{
Console.WriteLine(elem);
}
}
This outputs
key1
1
2
3
key2
4
5
Using LINQ SelectMany
to accumilate values into a single list:
foreach (string value in demo.SelectMany(kvp => kvp.Value))
{
Console.WriteLine(val);
}
Linq Solution includes Concat
to combine Key
and Values
into a single collection and SelectMany
to flatten them:
Dictionary<string, List<string>> demo = ...
var result = demo
.SelectMany(pair => new string[] { pair.Key }.Concat(pair.Value));
// Let's have a look
foreach (var item in result)
Console.WriteLine(item);
foreach (var item in demo )
{
WriteLine("loop");
WriteLine($"iterate though {item.key}");
WriteLine($"iterate though {item.Value}");
WriteLine();
}
This should output exactly what you want But, you could:
foreach (var item in demo )
{
WriteLine("loop");
WriteLine($"iterate though {item.key}");
if (item.Value is IEnumerable<string> val) foreach(var v in val) WriteLine(v);
WriteLine();
}
foreach (var item in demo)
{
Console.WriteLine("loop");
Console.WriteLine($"iterate though {item.Key}");
var valueAsString = $"[{String.Join(",", item.Value)}]";
Console.WriteLine($"iterate though {valueAsString}");
}
Output:
loop
iterate though key1
iterate though [1,2,3]
loop
iterate though key2
iterate though [4,5]
You can test: https://dotnetfiddle.net/REqIdD
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.