static readonly char[] TABLE = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ']', ',', '/', '.', '~', '&',
};
// Make a lookup dictionary of char => index in the table, for speed.
static readonly Dictionary<char, int> s_lookup = TABLE.ToDictionary(
c => c, // Key is the char itself.
c => Array.IndexOf(TABLE, c)); // Value is the index of that char.
static void Main(string[] args) {
// The test input string. Note it has no space.
string str = "hello,world.";
// For each character in the string, we lookup what its index in the
// original table was.
IEnumerable<int> indices = str.Select(c => s_lookup[c]);
// Print those numbers out, first converting them to two-digit hex values,
// and then joining them with commas in-between.
Console.WriteLine(String.Join(",", indices.Select(i => i.ToString("X02"))));
}
输出:
07,04,0B,0B,0E,1B,16,0E,11,0B,03,1D
请注意,如果您提供的输入字符不在查找表中,您不会立即注意到它! Select
返回一个IEnumerable
,只有当你去使用它时才会懒惰地评估它。此时,如果未找到输入字符,则字典[]
调用将抛出异常。
使这一点更明显的一种方法是ToArray()
在 Select 之后调用,因此您有一个索引数组,而不是IEnumerable
. 这将迫使评估立即发生:
int[] indices = str.Select(c => s_lookup[c]).ToArray();
参考: