只是添加另一个我认为更简单的解决方案:您可以再次消除零,然后将生成的可枚举转换为列表并在此列表上使用 IndexOf:
array.Where(x => x != 0)
.ToList().IndexOf(6); //Results in 5 as well
作为另一种我认为更漂亮的解决方案,您可以编写这样的扩展方法:
public static class Extensions
{
public static int IndexOfIgnoring<T> (this IEnumerable<T> collection, T indexOf, T toIgnore) =>
collection.Where (arg => !Equals (arg, toIgnore)).ToList ().IndexOf (indexOf);
}
你可以这样使用:
static void Main (string [] args)
{
Console.WriteLine ($"{new [] {1, 2, 3, 4, 0, 5, 0, 6, 7}.IndexOfIgnoring (6, 0)}");
Console.ReadLine ();
}
你可以阅读更多关于扩展方法here。
编辑正如 OP 的评论问我的那样,这是一个解决方案,在索引处设置项目,忽略特定项目。
因此我想再次使用扩展方法:
public static class Extensions
{
public static int IndexOfIgnoring<T> (this IEnumerable<T> collection, T indexOf, T toIgnore) =>
collection.Where (arg => !Equals (arg, toIgnore)).ToList ().IndexOf (indexOf);
public static int GetRealIndexOfIgnoring<T> (this IEnumerable<T> collection, int indexIgnored, T toIgnore)
=> collection.Select ((t, i) => new Tuple<T, int> (t, i)).Where (arg => !Equals (arg.Item1, toIgnore)).
ToList () [indexIgnored].Item2;
public static IEnumerable<T> SetAtIndexOfIgnoring<T> (this IEnumerable<T> collection, int indexIgnored, T toIgnore, T toSet)
{
var enumerable = collection as IList<T> ?? collection.ToList ();
return enumerable.Select ((t, i) => i == GetRealIndexOfIgnoring (enumerable, indexIgnored, toIgnore) ? toSet : t);
}
}
我们可以这样使用:
static void Main (string [] args)
{
var collection = new [] {1, 2, 3, 4, 0, 5, 0, 6, 7};
var ignoredIndex = collection.IndexOfIgnoring (6, 0);
Console.WriteLine ($"{ignoredIndex}");
collection = collection.SetAtIndexOfIgnoring(ignoredIndex, 0, 10).ToArray();
Console.WriteLine(string.Join(", ", collection));
Console.ReadLine ();
}
哪些输出:
5
1, 2, 3, 4, 0, 5, 0, 10, 7