[英]returning values from list for indexes that are outside the range of the list with C#
I have a list.我有一个清单。 If the value that you've entered is within that list - result will be returned.
如果您输入的值在该列表中 - 将返回结果。 Even if value is outside the result's range - result will be returned because of mod %.
即使值超出结果范围 - 由于 mod %,结果也会返回。 It's really hard to explain my problem with words, so lets take a look at the code :
很难用语言来解释我的问题,所以让我们看一下代码:
List<int> list1 = new List<int>(){ 0, 1, 2, 3, 4, 5, 6 };
int value = 3; // what's this number to us?
string result = "";
int starting_number = 3;
if (value == list1[(list1.IndexOf(starting_number) + 2) % list1.Count()])
{ result = "yeah"; }
else if (value == list1[(list1.IndexOf(starting_number) + 1) % list1.Count()])
{ result = "cool"; }
else if (value == list1[(list1.IndexOf(starting_number) + 0) % list1.Count()])
{ result = "one"; }
else if (value == list1[(list1.IndexOf(starting_number) - 1) % list1.Count()])
{ result = "noo"; }
else {result = "oops cant find it"; }
That's how it works:这就是它的工作原理:
starting_number = 3, value = 2 => result = "noo" (because 2 = IndexOf(starting_number)- 1) starting_number = 3, value = 2 => result = "noo" (因为 2 = IndexOf(starting_number)- 1)
starting_number = 6, value = 0 => result = "cool" (6 + 1 = 0) starting_number = 6, value = 0 => result = "cool" (6 + 1 = 0)
starting_number = 0, value = 6 => Error will occur. starting_number = 0, value = 6 =>会发生错误。 (0 - 1 = 6)
(0 - 1 = 6)
any ideas how to improve the code to get rid of this error?任何想法如何改进代码以消除此错误? Basically I can grab values is they are "after" starting_number, but I cant grab them "before" starting_number.
基本上我可以获取值是它们在 starting_number“之后”,但我不能在 starting_number“之前”获取它们。
in case of (6 + 1 = 0) : list looks like this 6,0,1,2,3...在(6 + 1 = 0)的情况下:列表看起来像这样 6,0,1,2,3...
in case of (0 - 1 = 6) : list should be this...4,5,6,0在(0 - 1 = 6)的情况下:列表应该是这个...4,5,6,0
if you have any questions please ask.. it's really hard to explain the problem with words, but I guess examples made it more clear.如果您有任何问题,请提问.. 用文字很难解释这个问题,但我想例子更清楚了。
how do you grab values that are below starting_number?你如何获取低于 starting_number 的值?
If I understand correctly, you want to map all integers to range 0 to Count-1 and your current formula is x % count
which works only when x > 0
.如果我理解正确,您希望 map 所有整数都在 0 到 Count-1 范围内,并且您当前的公式是
x % count
,它仅在x > 0
时有效。 Then if you want it to work for all values of x
try this one (x % count + count) % count
然后,如果您希望它适用于
x
的所有值,请尝试这个(x % count + count) % count
Try use this code尝试使用此代码
list1[Math.Sign((list1.IndexOf(starting_number) - 1))*(list1.IndexOf(starting_number) - 1) % list1.Count()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.