【问题标题】:add 3 to all integers in list without for loop c#将 3 添加到列表中的所有整数而没有 for 循环 c#
【发布时间】:2012-01-02 10:44:02
【问题描述】:

我想在不使用 for 循环或 foreach 循环的情况下为所有 list<int> 成员加 3?我可以在一行中做到这一点吗?如何?

【问题讨论】:

    标签: c# list for-loop


    【解决方案1】:

    某事某处将不得不循环。你不必循环你的代码,但有些东西必须这样做。

    我想不出任何可以修改列表中所有元素的临时方法,但是使用 LINQ 你可以轻松地创建一个 new List<int>

    var plusThree = originalList.Select(x => x + 3).ToList();
    

    或 pre-LINQ(效率稍高,但也更 List<T>-specific):

    var plusThree = originalList.ConvertAll(x => x + 3);
    

    但这两个都会在幕后循环播放。

    您可能会创建一个投影IList<T> 实现,懒惰地 应用投影(或者如果您想要真正花哨的话,可能是双射)...但这将是大量的工作。

    【讨论】:

    • 对于真正的“pre-LINQ”,你必须放弃 lambda。
    • @HenkHolterman:不——你仍然可以在面向 .NET 2 时使用 lambda 表达式,只要你有一个 C# 3+ 编译器。希望 OP 不再使用 Visual Studio 2005 :)
    【解决方案2】:

    您必须更改列表本身的值,因此没有其他方法可以在 for 循环中执行此操作,除非您被允许创建一个新列表,否则您可以使用 Linq(它将在它的自己的代码)。

    for(int i = 0; i < list.Count; i++) list[i]+=3;

    【讨论】:

      【解决方案3】:

      另一种方法(当然感觉就像在没有实际编写的情况下编写 foreach 循环)

       static void Main(string[] args)
          {
      
              List<int> list = new List<int>();
      
              list.Add(1);
              list.Add(2);
              list.Add(3);
              list.Add(4);
              list.Add(5);
      
      
      
              int k = 0;
              list.ForEach(delegate(int i) {  list[k++] = i+3; });
      
      
      
              foreach (var item in list)
              {
                  Console.WriteLine(item.ToString());
              }
      
              Console.ReadKey();
      
          }
      

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多