在這個類中,我定義了它在其中導航的字符串方法,並根據數字值生成一個字符串。如何將foreach循環轉換爲LINQ lambda
public class Class1
{
public string Returnstring (int number)
{
var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Test");
dictionary.Add(2, "TestTest");
dictionary.Add(3, "TestTestTest");
string somevalue = string.Empty;
foreach (var simple in dictionary)
{
while (number >= simple.Key)
{
somevalue += simple.Value;
number -= simple.Key;
}
}
return somevalue;
}
}
我只是想知道如何將foreach循環轉換爲LINQ lambda。
這是我爲班級寫的測試方法。
[TestMethod]
public void Given_1_when_Returnstring_Then_Should_Return_Test()
{
Class1 class1=new Class1();
string number = class1.Returnstring(1);
string expectedstring= "Test";
Assert.AreEqual(expectedstring, number);
}
那你試試?什麼沒有用?你所要求的非常簡單,只要你做了一些努力。 – 2013-05-09 09:50:40
即使你可以,你也不應該。 LINQ被設計成一個功能風格的框架,並且LINQ語句中的操作不應該有副作用。 – JLRishe 2013-05-09 09:59:40
這個代碼的目的是什麼?如果它看起來像重複第一個字典數字的值,然後忽略字典的其餘部分。 – JLRishe 2013-05-09 10:05:07