C#lambda和数组中的升序值

时间:2012-08-07 18:57:04

标签: c# lambda

我有一个数字数组,我想在其中找到第一个连续升序数的系列(计数多于一个)。

示例输入:{5, 1, 2, 4, 8, 7, 6, 9}
期望的输出:{1, 2, 4, 8}

2 个答案:

答案 0 :(得分:3)

这应该从给定的起始索引中找到第一个升序序列:

public static IEnumerable<int> GetAscending(IEnumerable<int> input, int startIndex)
{
    var ascending = input.Skip(startIndex)
        .Zip(input.Skip(startIndex + 1), (first, second) => new { Num = first, Next = second, Diff = second - first })
        .SkipWhile(p => p.Diff <= 0)
        .TakeWhile(p => p.Diff > 0)
        .Select(p => Tuple.Create(p.Num, p.Next))
        .ToArray();

    if(ascending.Length == 0) return Enumerable.Empty<int>();

    return ascending.Select(t => t.Item1).Concat(new int[] { ascending.Last().Item2 });
}

答案 1 :(得分:0)

public IEnumerable<int> getAscendingValues(IEnumerable<int> source)
{
    List<int> output = new List<int>();

    foreach (int next in source)
    {
        if (output.Count == 0 || output.Last() < next)
        {
            output.Add(next);
        }
        else
        {
            if (output.Count <= 1)
            {
                output.Clear();
            }
            else
            {
                return output;
            }
        }
    }

    if (output.Count > 1)
    {
        return output;
    }
    else
    {
        return null; //could also return an empty enumeration
    }
}

如果你想从一个特定的索引开始,你可以在调用它之前使用Skip方法,而不是添加额外的参数来支持它。 (即getAscendingValues(values.Skip(startIndex))