问题描述
如果项不存在,我对List<T>
的BinarySearch方法感到困惑.
I am confused about the BinarySearch method of List<T>
in case when the item does not exist.
我有
List<long> theList = {1, 3, 5, ...}.
theList.BInarySearch(0)
返回0,而theList.BInarySearch(3)
返回1,如预期.
theList.BInarySearch(0)
returns 0, and theList.BInarySearch(3)
returns 1, as expected.
但是,theList.BinarySearch(1)
返回 -2 ,而不是我期望的-1. MSDN手册中说:返回值:如果找到item,则排序列表中item的从零开始的索引;否则,为负数,它是大于item的下一个元素的索引的按位补码;如果不大,则为负元素,即Count的按位补码."
However, theList.BinarySearch(1)
returns -2, and not -1 as I'd expect. The MSDN manual says:"Return value: The zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."
按位补码"?我在这里想念什么,为什么是theList.BinarySearch(1) != -1
?
A "bitwise complement"? What Am I missing here and why is it that theList.BinarySearch(1) != -1
?
推荐答案
首先-您为什么期望-1?如果该项目是第一个项目,则它不能返回-0
(对于整数),因此可以推断第二个项目将返回-2.
First - why would you expect -1? If the item is the first item, it cannot return -0
(for integers), so it stands to reason -2 will be returned for the second item.
接下来,您可以使用~-2
-按位非运算符轻松获得正确的索引.
Next, you can easily get the right index by using ~-2
- the bitwise not operator.
这篇关于当找不到值时,C#List< T> .BinarySearch返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!