【问题标题】:How to compare elements in an array in C#?如何在 C# 中比较数组中的元素?
【发布时间】:2019-02-09 20:46:03
【问题描述】:

我会给你一个我想做的例子。如果我们有输入:

 1 4 3 2 

我想打印所有的数字,它们比它们的右边的所有元素更大。这里我们要打印 4, 32。我已将输入转换为数组,但我不知道如何比较元素。

 int[] numbers = Console.ReadLine()
            .Split()
            .Select(int.Parse)
            .ToArray();

【问题讨论】:

  • 使用两个for 循环怎么样?
  • 向后遍历数组并跟踪您迄今为止看到的最大值。当你遇到每个值时,检查它是否大于迄今为止的最大值,如果是,则存储它。以相反的顺序输出存储的数字。

标签: c# arrays linq


【解决方案1】:

您可以检查当前元素是否为数组右切片的最大值:

int[] numbers = new int[]{ 1, 4 ,3 ,2 };
var result=numbers.Where((number, i) => number == numbers.Skip(i).Max()).ToList();

输出:

4,3,2

【讨论】:

  • 如果数组中有不同的值则有效,否则您需要使用 All 方法
  • 这里怎么用All()?
  • int[] numbers = new int[] { 1, 4, 3, 2 }; var result = numbers.Where((number, i) => numbers.Skip(i+1).All(x=>x
【解决方案2】:
int[] numbers = Console.ReadLine()
            .Split()
            .Select(int.Parse)
            .ToArray();
        string[] topIntegers = new string[numbers.Length];
        int maximumValue = int.MinValue;
        int j = 0;
        for (int i = numbers.Length - 1; i >= 0; i--)
        {
            if (numbers[i] > maximumValue)
            {
                maximumValue = numbers[i];
                topIntegers[j] = maximumValue.ToString();
            }
            j++;
        }

        for (int i = topIntegers.Length - 1; i >= 0; i--)
        {
            Console.Write($"{topIntegers[i]} ");
        }

我是用这种方法做的,但我在这个测试中得到了错误的结果:

 14 24 3 19 15 17 
我的输出是:
 24 19 17 
但预期是:
 24 19 17 

【讨论】:

  • 不一样吗?
  • 不,看间隔。
  • 没有打断的意思,但是你看过我的回答了吗?它只需要 3 行代码就可以满足您的要求,这里的代码对于您的需要来说太复杂了。我已经逐行添加了解释,但如果您有任何不清楚的地方,请随时询问。
  • @Sergio0694,谢谢,不过我没用过,因为没学过LINQ,完全不懂。我应该使用数组来解决它。 :)
  • @NikolDimitrova:你的问题是你也在为数组中的空条目做你的 console.write 。然后为您的 topIntegers 数组中的每个空元素打印一个额外的空间。作为一个想法,您是否考虑过将它们添加到List<int>?这样,您将只拥有您想要的数字,而没有当前方法给您的间距。
【解决方案3】:

您可以使用 LINQ 做到这一点,如下所示:

var numbers = new[] { 1, 4, 3, 2 };
var query =
    from info in numbers.Select((n, i) => (n, i))
    where numbers.Skip(info.i + 1).All(value => info.n > value)
    select info.n;

它的工作方式是:

// Iterate over the numbers, keeping track of the index of each one
from info in numbers.Select((n, i) => (n, i))

// For each item, make sure it's greater than the ones on its right
where numbers.Skip(info.i + 1).All(value => info.n > value)

// If that's the case, select that item
select info.n;
```

【讨论】:

    【解决方案4】:

    您可以使用聚合来做到这一点:

    int[] allNumbers = new int[] { 1, 4, 3, 2 };
    int[] filteredNumbers = allNumbers.Aggregate(new List<int>(), (result, x) => {
        var filteredResult = new List<int>(result.Where(y => y > x));
        filteredResult.Add(x);
        return filteredResult;
    }).ToArray();
    

    【讨论】:

      猜你喜欢
      • 2020-07-16
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多