[英]C# - Get the Index of the last non-zero number of an array
I have an array of annual results which I would like to identify the index of the last non-zero value.我有一组年度结果,我想确定最后一个非零值的索引。 The 0 values at the end are an artifact of how the data is provided and read in. The 0 values can appear anywhere in the data, possibly even all 0s.末尾的 0 值是数据提供和读入方式的产物。0 值可以出现在数据中的任何位置,甚至可能全为 0。
decimal[] results = { 0, 0, 39.59m, -17.83m, 73.52m, 0, 56.80m, -61.54m, 0, 0, 0, 0 }
I've tried a few things but I keep ending up with the index of the value before the zero in the middle (eg 4, not 7).我已经尝试了一些事情,但我一直以中间零之前的值索引结束(例如 4,而不是 7)。
Here's the LINQ answer:这是 LINQ 的答案:
var index = results.Reverse().SkipWhile( x => x == 0 ).Count() - 1
decimal[] results = { 0, 0, 39.59m, -17.83m, 73.52m, 0, 56.80m, -61.54m, 0, 0, 0, 0 };
This approach uses a minimum of code这种方法使用最少的代码
var index = Array.FindLastIndex(results, value => value != 0);
This approach gives you both the value and the index这种方法为您提供了价值和索引
var lastIndexAndValue = results
.Select((value, index) => (index, value))
.LastOrDefault(item => item.value != 0);
You can create an extension method which can generically handle LastIndexOf
functionality.您可以创建一个可以通用处理LastIndexOf
功能的扩展方法。
public static class CustomExtensions
{
public static int LastIndexOf<T>(this T[] input, Func<T, bool> selector) where T : IComparable<T>
{
int lastIndex = -1;
for (int index = 0; index < input.Length; index++)
{
if (selector(input[index]))
{
lastIndex = index;
}
}
return lastIndex;
}
}
With this, you're essentially only updating the lastIndex
variable if the value at the index matches the condition (ie not equal to 0)有了这个,如果索引处的值与条件匹配(即不等于 0),您实际上只是更新lastIndex
变量
Usage用法
decimal[] results = { 0, 0, 39.59m, 17.83m, 73.52m, 0, 76.80m, 61.54m, 0, 0, 0, 0 };
int index = results.LastIndexOf(num => num != 0);
// Output is 7
You will probably need to iterate through the array with a for
loop.您可能需要使用for
循环遍历数组。 This should work:这应该有效:
int LastNonZero = -1;
for (int count = 0; count < results.Length; count++) {
if (results[count] != 0) // It isn't zero:
{
LastNonZero = count;
}
}
I just tested this and it returned 7.我刚刚对此进行了测试,它返回了 7。
I would just convert to List
and use linq
.我只想转换为List
并使用linq
。
var result = results.ToList().LastIndexOf(results.Last(c=> c != 0));
If you do not want to convert to list.如果您不想转换为列表。
var index = Array.LastIndexOf(results,results.Last(c=> c != 0));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.