在这个类中,我定义了它在其中导航的字符串方法,并根据数字值生成一个字符串。如何将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