-4

我如何将此循环转换为 Linq lambda 。

我已经定义了一个字典

    var dictionary = new Dictionary<int, string>();
        dictionary.Add(1,"Test");
        dictionary.Add(2,"Test2");
        dictionary.Add(3,"Test3");
        dictionary.Add(4,"Test4");

并希望通过它导航并根据数字值制作一个字符串

       int number = 10; // I am hard coded this number for this example
       string somevalue = string.Empty;
       int somekey = 0;

   foreach (var simple in dictionary )
         {
             while (number>=simple.Key)
             {
                  somevalue += simple.Value;
                  somekey -= simple.Key;
             }
         }
   }

它适用于简单的循环并且会返回Test4Test4Test2,只需将其转换为 lambda 表达式。

4

1 回答 1

0

我想你想要这个:

List<string> list = dictionary
   .Select(kv => string.Join("", Enumerable.Repeat(kv.Value, kv.Key)))
   .ToList();

与您一起样品:("Test"如果TestTest键是2)

但是,您的循环无法编译,并且number当键已经指示重复次数时,您需要什么并不清楚。

于 2013-05-08T23:08:05.740 回答