C# 在长[]数组中查找索引
我有一个long[]类型的数组,有19组数字,然后是另一个char[]类型的数组,当用户输入“45324”时,我需要在long[]数组中找到该输入的索引,并将索引传递给char[]数组,然后在该位置输出值 所以45324索引可能是12,char[]数组中的第12项可能是“#”,我尝试了循环,但pfft每次尝试都失败了。我希望不必重写代码并将所有这些值重新硬编码到不同类型的数组中。C# 在长[]数组中查找索引,c#,.net,arrays,C#,.net,Arrays,我有一个long[]类型的数组,有19组数字,然后是另一个char[]类型的数组,当用户输入“45324”时,我需要在long[]数组中找到该输入的索引,并将索引传递给char[]数组,然后在该位置输出值 所以45324索引可能是12,char[]数组中的第12项可能是“#”,我尝试了循环,但pfft每次尝试都失败了。我希望不必重写代码并将所有这些值重新硬编码到不同类型的数组中。for(int I=0;I
for(int I=0;Iint index = Array.IndexOf(array, long.Parse("45324"));
{
if(longArray[i].ToString()==输入)
{
返回i;
}
}
返回-1;
您可以使用
Array.IndexOf
来确定数组中值的索引
long numberValue;
// First parse the string value into a long
bool isParsed = Int64.TryParse(stringValue, out numberValue);
// Check to see that the value was parsed correctly
if(isParsed)
{
// Find the index of the value
int index = Array.IndexOf(numberArray, numberValue);
// Check to see if the value actually even exists in the array
if(index != -1)
{
char c = charArray[index];
// ...
}
}
那么:
long input = Int64.Parse("45324");
int index = Array.IndexOf(long_array, input);
char output = default(char);
if(index != -1)
output = char_array[index];
或:
long input=Int64.Parse(“45324”);
int指数=-1;
for(int i=0;i
如果数据变化不大,您可以使用Linq将结果转换为字典,从而根据用户输入的字符串执行快速查找
假设长数组名为longs
,字符数组名为chars
var dict=longs
.Select((x,i)=>new {Key=x.ToString(),Value=chars[i]})
.ToDictionary(x=>x.Key,x=>x.Value);
现在您可以使用输入字符串进行检查
e、 g
或
请发布您当前的代码并解释您的卡在哪里。查看
Array.IndexOf()
方法,然后使用数组索引器访问字符数组。。。完成。当我们有可用的Array.IndexOf
时,为什么要循环?@davenewza-显示了一种替代的低级方法。并非所有ANSWR都必须相同。这是非常正确的,但有些替代方案比其他方案复杂得多。您的long
参数到TryParse
应该是out
参数。以上内容将无法编译。
long input = Int64.Parse("45324");
int index = -1;
for(int i = 0; i < long_array.Length; i++){
if(long_array[i] == input){
index = i;
break;
}
}
char output = default(char);
if(index != -1)
output = char_array[index];
var dict=longs
.Select((x,i)=>new {Key=x.ToString(),Value=chars[i]})
.ToDictionary(x=>x.Key,x=>x.Value);
if (!dict.ContainsKey(userInput)) // value not in the collection
char value= dict[userInput];