【问题标题】:Improving a simple C# program [closed]改进一个简单的 C# 程序 [关闭]
【发布时间】:2018-08-18 22:40:52
【问题描述】:

我刚刚开始学习用 C# 编程,我创建了一个非常简单的程序,它假设总结了 int 数组中的所有正数。

程序看起来像这样:

static void Main(string[] args)
{
    int[] intArr = new int[5] { 1, 2, 3, -1, 0 };
    int result = Sum(intArr);
    Console.WriteLine("The total sum of the array is: {0}", result);
    Console.ReadKey();
}

public static int Sum(int[] intArr)
{
    int sum = 0;
    for(int i =0; i < intArr .Length; i++)
    {
        if(values[i]>0)
        {
            sum += intArr[i];
        }
    }
     return sum;
}

有什么办法可以让这个程序变得更小或改进它的逻辑?

【问题讨论】:

  • 我投票结束这个问题,因为它属于 codereview.stackexchange.com
  • @RogerLipscombe 啊好吧!如果这是一个错误的帖子,请删除它。
  • @anderssinho 版主和一些高级用户可以将帖子移动到不同的堆栈。

标签: c# function summarize


【解决方案1】:

不过,您无法对算法进行太多改进。由于您要对所有数组元素求和,因此您需要对它们中的每一个元素至少迭代一次,尽您所能将您置于 O(n) 中。

代码本身也不能优化太多。至于让它更小,你可以考虑使用 Linq 和 lambda 表达式:

// ...
int result = intArr.Where(i => i > 0).Sum();

lambda 表达式 (i =&gt; i &gt; 0) 与 Where() 一起设置了一个谓词(条件),它告诉程序对所有元素 (i) 求和,其中 i 是一个正整数 (=&gt; i &gt; 0)。

但这否定了编写自己的函数的目的。如果没有必要,您甚至可以使用单线:

Console.WriteLine("The total sum of the array is: {0}", new int[] { 1, 2, 3, -1, 0 }.Where(i => i > 0).Sum());

此外,由于您正在使用值初始化数组,因此不需要如上所示提及数组长度。不是真正的优化,只是一个提示。

【讨论】:

  • OP 的要求是“汇总所有正数”,您至少需要一个过滤器。
  • 完全错过了。谢谢。 :3
  • Sum(boolean) 不起作用。 Sum(nullable) 有效:new[] { 1, 2, 3, -1, 0 }.Sum(x => (x > 0) ? (int?)x : null)}"
  • @AxCoder Rusty 一年多后重返 SO。在桌面上写会更好。无论如何,谢谢。
  • @Farhan Anam JFYI,现在有一个try.dot.net 站点可以在没有 IDE 的情况下测试代码 sn-ps
【解决方案2】:

对于典型的可枚举操作,您可以使用 LINQ。由于您可以链接运算符,因此您可以很容易地先过滤然后求和。

使用常见的 LINQ 运算符意味着代码比手写的 sn-ps 更具可读性和可维护性。

int[] intArr = new int[5] { 1, 2, 3, -1, 0 };

int result = intArr.Where( i => i > 0 ).Sum();

Console.WriteLine(result);

【讨论】:

    【解决方案3】:

    使用静态导入和字符串插值

    using static System.Math;
    using System.Linq;
    using static System.Console;
    namespace ConsoleApp4
    {
        class Program
        {
            static void Main(string[] args)
            {
                WriteLine($"The total sum of the array is: { new[] { 1, 2, 3, -1, 0 }.Sum(x => Max(0, x))}");
                ReadKey();
            }
        }
    }
    

    附加变量更具可读性:

    var total = new[] { 1, 2, 3, -1, 0 }.Sum(x => Max(0, x));
    WriteLine($"The total sum of the array is: {total}");
    

    【讨论】:

      【解决方案4】:

      您可以使用 lambda 表达式改进代码。

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text.RegularExpressions;
      
      namespace Rextester
      {
          public class Program
          {
              public static void Main(string[] args)
              {
                  int[] intArr = new int[5] { 1, 2, 3, -1, 0 };
                  int result =  intArr.AsParallel().Where(i => i > 0).Sum();
                  Console.WriteLine("The total sum of the array is: {0}", result);
              }
          }
      }
      

      如果数组的长度很大,则可以使用 AsParallel() 来划分数组并在处理核心之间共享求和运算。

      https://www.dotnetperls.com/asparallel

      【讨论】:

      • 你必须提供一个例子来说明你的意思,似乎不清楚 OP 应该在哪里使用 lambda 表达式(或者它将如何改进代码)
      • 完成。另一方面,这段代码的最佳优化是直接显示结果,因为元素总是相同的元素......结果总是相同的:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2010-09-27
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多