简体   繁体   中英

How to compare elements in an array in C#?

I will give you an example of what I want to do. If we have as input:

1 4 3 2

I want to print all the numbers which are bigger than all the elements to their right . Here we have to print 4, 3 and 2 . I've converted the input to an array, but I don't know how to compare the elements.

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

You can check if the current element is maximum of right slice of array :

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

Output:

4,3,2

You can do that using LINQ, like this:

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;

The way this works is:

// 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;
```
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]} ");
        }

I made it in this way but I got incorrect results on this test:

14 24 3 19 15 17
My output is:
 24 19 17  
but expected is:
 24 19 17  

You can do this using Aggregate:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM