Help with a small problem...
I have a method that returns a dictionary. I need to rewrite it in such a way that I can enumerate the result of this method using await foreach
. Please help me, something is not working for me at all.
It's my method:
public IDictionary<long, long> TransformListInDictionary(IList<string> list)
{
var result = new Dictionary<long, long>();
foreach (var member in list)
{
var idx = member.IndexOf(':');
var key = member.Substring(0, idx);
var value = member.Substring(idx + 1);
result.Add(Convert.ToInt64(key), Convert.ToInt64(value));
}
return result;
}
To use a dictionary in an await foreach
loop, this method requires a return value of IAsyncEnumerable<KeyValuePair<long,long>>
.
Therefore, I have a question, how to rewrite the method published above is the return value.
Why do I need it.
I have some code which I am posting below. I'll try to describe my idea.
When the code enters the for loop, it does some work and instantiates the dictionary. Which is further processed in the foreach loop.
var logic = new AllLogic();
var variable = Convert.ToInt32(Console.ReadLine());
var randomSecundForPause = new Random();
for (int i = 0; i < variable; i++)
{
var list = new List<string>();
var dict = logic.TransformListInDictionary(list);
//some code
foreach (var item in dict)
{
try
{
//some code
Thread.Sleep(randomSecundForPause.Next(100000, 150000));
}
catch (Exception e)
{
//some code
Thread.Sleep(randomSecundForPause.Next(100000, 150000));
}
}
}
I would like this foreach loop to run in the background and the main code flow to go to a new iteration of the for loop.
As I understand it, I need to replace foreach with await foreach.