Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While Loop with assignment in C# Linq

I'd like to assign the variable vStreamID with a random number. This number should be newly generated as long as my dictionary md_StreamDict contains the generated number.

Long version:

vStreamID = (new Random()).Next(1000, 9999).ToString();
while (md_StreamDict.ContainsKey(vStreamID)) {
    vStreamID = (new Random()).Next(1000, 9999).ToString();
}

I would like to see something LINQ style

md_StreamDict.ContainsKey(vStreamID)
    .while( x => x = (new Random())
    .Next(1000, 9999)
    .ToString();

I know the example above is bananas. But I would be happy if there's a real way to achieve this. And no, we're not starting the usual discussion about readability again. ;)

like image 550
Neurodefekt Avatar asked Dec 07 '22 10:12

Neurodefekt


1 Answers

If I understand you right You just need a number in well known range and this number should not be already in a dictionary, so do this without Random:

Enumerable.Range(1000, 9999)
          .Where(n => !dict.ContainsKey(n))
          .FirstOrDefault();
like image 166
sll Avatar answered Dec 08 '22 22:12

sll