我真的無法解決這個問題。我有一個字典,我已經保存了一個編碼表。我正在嘗試爲密鑰獲得正確的值。 帶有不同where子句的if-子句應該100%導致結果,但它不。 where子句被忽略了嗎?LINQ詞典中的Where-Clauses不能正常工作
public static string ByteArrayToHex(byte[] bytes)
{
StringBuilder Result = new StringBuilder(bytes.Length * 2);
string HexAlphabet = "ABCDEF";
foreach (byte B in bytes)
{
Result.Append(HexAlphabet[(int)(B >> 4)]);
Result.Append(HexAlphabet[(int)(B & 0xF)]);
}
return Result.ToString();
}
static void Main(string[] args)
{
List<byte> byteList2 = new List<byte>() { 227, 129,130 };
List<byte> byteList = new List<byte>() {131, 95, 131, 126, 129, 91};
string filename = "file.txt";
var dict = Shared.IO.Read.EncodingTable(filename);
var original = Encoding.GetEncoding(932).GetString(byteList.ToArray());
var custom = CustomConverter(byteList, dict);
var original2 = Encoding.GetEncoding(932).GetString(byteList2.ToArray());
var custom2 = CustomConverter(byteList2, dict);
Console.WriteLine("Original: " + original);
Console.WriteLine("Custom: " + custom);
Console.WriteLine("Original: " + original2);
Console.WriteLine("Custom: " + custom2);
Console.ReadKey();
}
static string CustomConverter(List<byte> byteList, Dictionary<string,string> dict)
{
var result = string.Empty;
while (byteList.Count != 0)
{
var count = byteList.Count;
byte[] bytes = new byte[] { };
if (count > 2) bytes = new byte[3] {byteList[0], byteList[1], byteList[2]};
if (count == 2) bytes = new byte[2] {byteList[0], byteList[1]};
if (count == 1) bytes = new byte[1] {byteList[0]};
var hexString = Shared.IO.Convert.ByteArrayToHex(bytes);
KeyValuePair<string,string> entry;
if (hexString.Length > 2)
{
var a = hexString.Substring(0, 4);
var b = hexString.Substring(0, 2);
var c = hexString.Substring(0, 1);
entry = (from item in dict
where item.Key == hexString || item.Key == a || item.Key == b || item.Key == c
select item).First();
}
else
{
var a = hexString.Substring(0, 1);
entry = (from item in dict
where item.Key == hexString || item.Key == a
select item).First();
}
byteList.RemoveRange(0, (entry.Key.Length/2));
result = result + entry.Value;
}
return result;
}`
public static Dictionary<string, string> EncodingTable(string filename)
{
string directory = Environment.CurrentDirectory + @"\encoding\";
string path = directory + filename;
Dictionary<string,string> encodingTable = new Dictionary<string, string>();
var lines = System.IO.File.ReadAllLines(path);
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line)) continue;
if (line.StartsWith("#")) continue;
var lineArray = line.Split(';');
encodingTable.Add(lineArray[0], lineArray[1]);
}
return encodingTable;
}`
字典包含這樣的事情
79;か 7A;き 7B;く 7C;け 7D;こ 7E;さ 7F;し 80;す 81 ;せ 82;そ 83;た 84;ち
請發表[mcve]。我們需要查看該字典中的密鑰以及您嘗試匹配哪些字節。另外,發佈'ByteArrayToHex'返回的內容。 –
你能用我們可以用來重現你的結果的東西來更新你的代碼示例嗎?實際上,我們不知道'hexString'的值是什麼,或者字典包含什麼。填充字典的簡短方法會很有幫助。 –
「ByteArrayToHex」返回什麼?我假設這是一個字符串,因爲有'Substring'調用,但是如果長度大於2,則調用'Substring(0,1)'。是否檢查過'a','b','c'的值調試器確保它們是你期望它們的東西? –