假設我們有一個List<int>內容 like[0,0,0,0,1,1,1,1,0,0,0,1,2,2,0,0,2,2]并且我們想要第 n 個不為零的數字的索引。
例如,GetNthNotZero(3)應該回傳 6。
使用 for 回圈會很容易,但我覺得應該有一個 LINQ 來完成它。使用 LINQ 陳述句可以實作嗎?
uj5u.com熱心網友回復:
沒有開箱即用的方法,但是您是否考慮過撰寫自己的擴展方法來提供類似于 LINQ 的東西FindIndex()?
class Program
{
static void Main(string[] args)
{
var list = new List<int>{ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 2, 2, 0, 0, 2, 2 };
var index = list.FindNthIndex(x => x > 0, 3);
}
}
public static class IEnumerableExtensions
{
public static int FindNthIndex<T>(this IEnumerable<T> enumerable, Predicate<T> match, int count)
{
var index = 0;
foreach (var item in enumerable)
{
if (match.Invoke(item))
count--;
if (count == 0)
return index;
index ;
}
return -1;
}
}
uj5u.com熱心網友回復:
實際上,您可以使用標準 LINQ 做到這一點,您可以使用:
List<int> sequence = new List<int>{0,0,0,0,1,1,1,1,0,0,0,1,2,2,0,0,2,2};
int index = sequence.Select((x, ix) => (Item:x, Index:ix))
.Where(x => x.Item != 0)
.Skip(2) // you want the 3rd, so skip 2
.Select(x => x.Index)
.DefaultIfEmpty(-1) // if there is no third matching condition you get -1
.First(); // result: 6
uj5u.com熱心網友回復:
這當然是可能的,但 Linq 方法會使它變得更加復雜。這是顯式回圈更好的情況之一。
使用 Linq 引起的兩個顯著并發癥是:
- 處理空序列或沒有零的序列。
- 合成要使用的索引。
Linq 解決方案可能如下所示(但請注意,使用 Linq 可能有許多不同的可能方法):
using System;
using System.Collections.Generic;
using System.Linq;
public static class Program
{
public static void Main()
{
var ints = new List<int> { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 2, 2, 0, 0, 2, 2 };
Console.WriteLine(IndexOfNthNotZero(ints, 3)); // 6
Console.WriteLine(IndexOfNthNotZero(Enumerable.Repeat(0, 10), 3)); // -1
Console.WriteLine(IndexOfNthNotZero(ints, 100)); // -1
Console.WriteLine(IndexOfNthNotZero(Array.Empty<int>(), 0)); // -1
}
public static int IndexOfNthNotZero(IEnumerable<int> sequence, int n)
{
return sequence
.Select((v, i) => (value:v, index:i)) // Synthesize the value and index.
.Where(item => item.value != 0) // Choose only the non-zero value.
.Skip(n-1) // Skip to the nth value.
.FirstOrDefault((value:0, index:-1)).index; // Handle missing data by supplying a default index of -1.
}
}
請注意,此實作回傳-1以指示未找到合適的值。
將其與簡單的回圈實作進行比較,我認為您會同意使用簡單的回圈更好!
public static int IndexOfNthNotZero(IReadOnlyList<int> sequence, int n)
{
for (int i = 0; i < sequence.Count; i)
if (sequence[i] != 0 && --n == 0) // If element matches, decrement n and return index if it reaches 0.
return i;
return -1;
}
或者,如果您愿意(避免預先遞減):
public static int IndexOfNthNotZero(IReadOnlyList<int> sequence, int n)
{
for (int i = 0, numberOfMatches = 0; i < sequence.Count; i)
{
if (sequence[i] != 0) // If condition matches
if ( numberOfMatches == n) // Increment number of matches, and if it reaches n
return i; // then return the current index
}
return -1;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/446625.html
