简体   繁体   English

如何获取字符列表或列表中的特定字符<char></char>

[英]How to get the specific char in char list or List<char>

List<char> pc = new List<char>();
            pc.Add('?');
            pc.Add(';');
            pc.Add(',');

return pc.Contains(Convert.ToChar(temp)) ? pc[Convert.ToChar(temp)].ToString() : null;

(above code in the method which return string) (上面返回字符串的方法中的代码)

Normally in string list I get any specific value from List[] but in this it's changing the char into int.通常在字符串列表中,我从 List[] 获得任何特定值,但在此它将 char 更改为 int。

example: pc['?'] == pc[63] due to this ArgumentOutOfRangeException occur.例如: pc['?'] == pc[63] 由于这个 ArgumentOutOfRangeException 发生。

So, how I get the specific char from my char list?那么,我如何从我的字符列表中获取特定的字符?

Thanks in advance提前致谢

A char holds an integral value, but the index of your list is not equal to the value of the char it's holding. char 拥有一个整数值,但列表的索引不等于它所拥有的 char 的值。 Your list looks like this, with [index] => value :您的列表如下所示,带有[index] => value

[0] => 63
[1] => 59
[2] => 44

You'll have to scan the list:您必须扫描列表:

var charToFind = Convert.ToChar(temp);
char? match = pc.FirstOrDefault(c => c == charToFind);

If you want to know the index, ask for the index:如果您想知道索引,请索要索引:

int index = pc.IndexOf(charToFind); // -1 for not found

But then if you have the desired char in temp (or charToFind ) already, there's no need to obtain it from the list again, you can just return the char if it's present in the list:但是,如果您已经在temp (或charToFind )中有所需的 char ,则无需再次从列表中获取它,如果列表中存在该 char ,则可以返回:

return pc.Contains(charToFind) ? charToFind.ToString() : null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM