C# 如何将foreach循环转换为LINQ lambda

C# 如何将foreach循环转换为LINQ lambda,c#,linq,C#,Linq,在这个类中,我定义了string方法,它在其中导航并根据数值生成一个字符串 public class Class1 { public string Returnstring (int number) { var dictionary = new Dictionary<int, string>(); dictionary.Add(1, "Test"); dictionary.Add(2, "TestTest");

在这个类中,我定义了string方法,它在其中导航并根据数值生成一个字符串

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

我的理解是否正确,您希望以下输入具有以下输出

输入:1 输出:测试

投入:2 输出:TestTest

投入:3 输出:testtest

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

试试这个:

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

无论您的算法是否错误,它本质上是重复字典中第一项的值n次n是传入的number参数

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

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

你试了什么?什么不起作用?你所要求的很简单,只要你付出一些努力。即使你能,你也不应该。LINQ被设计成一个函数式的框架,LINQ语句中的操作不应该有副作用。那么这段代码的目的是什么?If看起来像是将第一个字典的值重复了几次,然后忽略了字典的其余部分。为什么需要在那里使用LINQ?LINQ中没有foreach方法,如上所述,查询不应该产生副作用,但也不要超前。您可以不使用foreach,而是将您拥有的集合(即列表和字典)筛选到您需要的集合(例如Where、Join、Select等),然后执行一些操作(例如Sum)。在某些情况下,您确实需要使用foreach进行迭代,但大多数情况下;只需通过LINQ过滤数据就足够了。
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();
        }
    }
string somevalue = string.Join("", Enumerable.Repeat(dictionary.First().Value, number));