使用 FindLast 等方法时如何区分找到的 0 和默认值(int)?
How to distinguish between a found 0 and default(int) when using methods like FindLast?
我有一个整数列表,我需要找到与谓词匹配的最后一次出现。用一个很简单的例子:
var myList = new List<int> { 1, 5, 6, 20, 18, 2, 3, 0, 4 };
var lastMatch = myList.FindLast(e => e == 0 || e == 2);
这似乎是 FindLast
的完美用例。问题是这个方法 returns default(T)
如果什么都没找到,在整数的情况下,它实际上是一个有效值 0
。所以问题是,如果这个方法 returns 0
,我怎么知道它是否找到了东西?有没有更好的方法来处理这种情况?
改用FindLastIndex
。如果索引为负,则未找到匹配项。如果它不是负数:那就是你想要的索引,所以:使用带有该索引的索引器。
作为@MarcGravell 回答的替代:
您可以使用将谓词作为参数的 Linq Last
扩展方法重载,而不是 List FindLast
方法。如果找不到匹配项,它将抛出异常。
在一般情况中,当我们有IEnumerable<T>
和任意 T
时(我们不能玩把戏现在 int?
)
我们可以实现一个 扩展方法 :
public static partial class EnumerableExtensions {
public static int LastIndex<T>(this IEnumerable<T> source,
Predicate<T> predicate) {
if (source is null)
throw new ArgumentNullException(nameof(source));
if (predicate is null)
throw new ArgumentNullException(nameof(predicate));
int result = -1;
int index = -1;
foreach (T item in source) {
index += 1;
if (predicate(item))
result = index;
}
return result;
}
}
然后
var lastMatch = myList.LastIndex(e => e == 0 || e == 2);
我有一个整数列表,我需要找到与谓词匹配的最后一次出现。用一个很简单的例子:
var myList = new List<int> { 1, 5, 6, 20, 18, 2, 3, 0, 4 };
var lastMatch = myList.FindLast(e => e == 0 || e == 2);
这似乎是 FindLast
的完美用例。问题是这个方法 returns default(T)
如果什么都没找到,在整数的情况下,它实际上是一个有效值 0
。所以问题是,如果这个方法 returns 0
,我怎么知道它是否找到了东西?有没有更好的方法来处理这种情况?
改用FindLastIndex
。如果索引为负,则未找到匹配项。如果它不是负数:那就是你想要的索引,所以:使用带有该索引的索引器。
作为@MarcGravell 回答的替代:
您可以使用将谓词作为参数的 Linq Last
扩展方法重载,而不是 List FindLast
方法。如果找不到匹配项,它将抛出异常。
在一般情况中,当我们有IEnumerable<T>
和任意 T
时(我们不能玩把戏现在 int?
)
我们可以实现一个 扩展方法 :
public static partial class EnumerableExtensions {
public static int LastIndex<T>(this IEnumerable<T> source,
Predicate<T> predicate) {
if (source is null)
throw new ArgumentNullException(nameof(source));
if (predicate is null)
throw new ArgumentNullException(nameof(predicate));
int result = -1;
int index = -1;
foreach (T item in source) {
index += 1;
if (predicate(item))
result = index;
}
return result;
}
}
然后
var lastMatch = myList.LastIndex(e => e == 0 || e == 2);