C# 在列表中查找编号开始上升的索引
假设我有一个数字列表,我想知道列表中的数字从哪里开始减少,没有特定的顺序,举个例子会很理想C# 在列表中查找编号开始上升的索引,c#,linq,C#,Linq,假设我有一个数字列表,我想知道列表中的数字从哪里开始减少,没有特定的顺序,举个例子会很理想 1, 2, 2, 3, 3, 4, 4, 5, 5, 4, <= this should be my output 4, 3, 3, 2, 2, 1, 1, 2. 2. 3. 3. 4. 4. 5. 5. 4、不是林克,而是C#way: public int FirstDecreasingIndex(IList myList) { 对于(int i=0;imyList[i+1]) 返回i+1; }
1,
2,
2,
3,
3,
4,
4,
5,
5,
4, <= this should be my output
4,
3,
3,
2,
2,
1,
1,
2.
2.
3.
3.
4.
4.
5.
5.
4、不是林克,而是C#way:
public int FirstDecreasingIndex(IList myList)
{
对于(int i=0;imyList[i+1])
返回i+1;
}
返回-1;//或其他值
}
对于此输入:
{1,2,3,2,4,5,6,7,8,9}
函数将返回3
,因为它是列表第一次开始减少的第一个索引。您可以在IEnumerable
上创建自己的扩展方法
公共静态类MyEnumerable
{
公共静态IEnumerable递减(此IEnumerable源)
其中TSource:i可比较
{
使用(var e=source.GetEnumerator())
{
TSource-previous;
if(如MoveNext())
{
先前=e.当前;
while(如MoveNext())
{
如果(上一个与(e.电流)>0相比)
收益率,收益率,电流;
先前=e.当前;
}
}
}
}
}
用法
var input = new List<int>() { 1, 2, 3, 2, 4, 5, 6, 7, 8, 9 };
var firstDescending = input.Descending().First();
var input=newlist(){1,2,3,2,4,5,6,7,8,9};
var firstDescending=input.Descending().First();
不完全是linq,但我认为已经足够接近了
var list = new List<int> { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
var index = Enumerable.Range(0, list.Count).First(i => i > 0 && list[i] < list[i - 1]);
var list=新列表{1,2,3,4,5,4,3,2,1};
var index=Enumerable.Range(0,list.Count)。首先(i=>i>0&&list[i]
这里是一个使用可枚举的“一行程序”。聚合和元组:s:
var numbers = new[] { 1, 2, 2, 3, 3, 4, 4, 5, 5, 4, 4, 3, 3, 2, 2, 1 };
var idx = numbers.Aggregate(Tuple.Create(true, 0, 0), (tuple, x) =>
tuple.Item1
? tuple.Item3 <= x
? Tuple.Create(true, tuple.Item2 + 1, x)
: Tuple.Create(false, tuple.Item2, x)
: tuple)
.Item2;
var number=new[]{1,2,2,3,3,4,4,5,5,4,4,3,3,2,2,1};
var idx=numbers.Aggregate(Tuple.Create(true,0,0),(Tuple,x)=>
tuple.Item1
?tuple.Item3对于真正的功能性方法:
List<int> numbers = ...;
var firstDecreasingValue =
numbers.Skip(1).Zip(numbers, (number, previous) => new { number, previous })
.Where(x => x.number.CompareTo(x.previous) < 0)
.Select(x => x.number)
.First();
列表编号=。。。;
var第一递减值=
numbers.Skip(1).Zip(numbers,(number,previous)=>new{number,previous})
其中(x=>x.number.CompareTo(x.previous)<0)
.选择(x=>x.number)
.First();
为什么不使用简单的for循环?序列总是这样吗?如果是这样,你可以尝试获取最高值并返回到以前的最高值。你是否已经尝试了任何东西并进行了叠加,或者只是发布了一个问题以获得完整解而不做任何工作?Dean,1,4,2,5,3,6
的代码应该打印什么?@marcin,是的我用for循环实现了它,但我更感兴趣的是一个使用linq的示例,因为我的输入是一个可枚举的数据范围,如果我表现得懒惰或笨拙,很抱歉。它不应该返回2而不是3吗?不看看这个问题。第一个数字的索引低于它的前一个数字是wanted,不清楚OP want是值还是indexHe想知道第一个开始减少的项目。或者他想知道该索引的值。如果是这样,它应该返回myList[i+1]
@MarcinJuraszek:看看这个主题,你不必对它的可比性设置限制。最好使用a。谢谢你的回复!
var numbers = new[] { 1, 2, 2, 3, 3, 4, 4, 5, 5, 4, 4, 3, 3, 2, 2, 1 };
var idx = numbers.Aggregate(Tuple.Create(true, 0, 0), (tuple, x) =>
tuple.Item1
? tuple.Item3 <= x
? Tuple.Create(true, tuple.Item2 + 1, x)
: Tuple.Create(false, tuple.Item2, x)
: tuple)
.Item2;
List<int> numbers = ...;
var firstDecreasingValue =
numbers.Skip(1).Zip(numbers, (number, previous) => new { number, previous })
.Where(x => x.number.CompareTo(x.previous) < 0)
.Select(x => x.number)
.First();