【问题标题】:How can I convert foreach loop to LINQ lambda如何将 foreach 循环转换为 LINQ lambda
【发布时间】:2013-05-09 19:16:09
【问题描述】:

在这个类中,我定义了它在其中导航的字符串方法,并根据数字值创建一个字符串。

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);
}

【问题讨论】:

  • 你尝试了什么?什么没用?你所要求的很简单,只要你付出一些努力。
  • 即使可以,也不应该。 LINQ 被设计成一个函数式框架,LINQ 语句中的操作不应该有副作用。
  • 这段代码的目的是什么?如果看起来它重复第一个字典的值number 次,然后忽略字典的其余部分。
  • 为什么需要在那里使用 LINQ?
  • LINQ 中没有 foreach 方法(如上所述,查询不应该产生副作用),但不要超越自己。 你可以做什么而不是使用 foreach 是过滤你拥有的集合(即列表和字典)到你需要的东西(例如WhereJoinSelect 等)然后执行一些操作(例如Sum)。在某些情况下,您确实需要使用 foreach 进行迭代,但大多数情况下;只需通过 LINQ 过滤数据就足够了。

标签: c# linq


【解决方案1】:

我的理解是否正确,您希望以下输入获得以下输出?

输入:1 输出:测试

输入:2 输出:TestTest

输入:3 输出:TestTestTest

如果是这样,为什么不直接使用somevalue = dictionary[number]

【讨论】:

    【解决方案2】:

    试试这个:

    return string.Join("", dictionary.Take(number).Select(x=>x.Value));
    

    【讨论】:

      【解决方案3】:
      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();
              }
          }
      

      【讨论】:

        【解决方案4】:

        无论你的算法是否正确,它本质上所做的就是重复Dictionaryn中第一项的值的次数(n是传入的number参数)。

        如果这实际上是您想要做的,那么您可以简单地做:

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

        【讨论】: