2013-05-09 64 views
1

在這個類中,我定義了它在其中導航的字符串方法,並根據數字值生成一個字符串。如何將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); 
} 
+2

那你試試?什麼沒有用?你所要求的非常簡單,只要你做了一些努力。 – 2013-05-09 09:50:40

+0

即使你可以,你也不應該。 LINQ被設計成一個功能風格的框架,並且LINQ語句中的操作不應該有副作用。 – JLRishe 2013-05-09 09:59:40

+0

這個代碼的目的是什麼?如果它看起來像重複第一個字典數字的值,然後忽略字典的其餘部分。 – JLRishe 2013-05-09 10:05:07

回答

0

我的理解是否正確,您希望以下輸出用於以下輸入?

輸入:1個 輸出:測試

輸入:2 輸出:TESTTEST

輸入:3 輸出:TestTestTest

如果是這樣,爲什麼不使用somevalue = dictionary[number]

0

試試這個:

return string.Join("", dictionary.Take(number).Select(x=>x.Value)); 
0
internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      dictionary.Add(1, "Test"); 
      dictionary.Add(2, "TestTest"); 
      dictionary.Add(3, "TestTestTest"); 

      Console.WriteLine("{0}", ReturnResult(3)); 
     } 

     public static Dictionary<int, string> dictionary = new Dictionary<int, string>(); 

     public static string ReturnResult(int index) 
     { 
      return dictionary.Where(x => x.Key.Equals(index)).Select(res => res.Value).First(); 
     } 
    } 
0

無論你的算法是不正確或不,它實際上做的是重複的Dictionaryn次數第一項的值(n作爲number參數通過)。

如果這是事實,你想做的事,那麼你可以簡單地做:

string somevalue = string.Join("", Enumerable.Repeat(dictionary.First().Value, number));