2010-10-08 67 views
1

這似乎是.NET 2.0不支持字典鍵OrderByDescending,我怎樣才能改變這種代碼到.NET 2.0更改代碼以.NET 2.0

private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>() 
{ 
    { new byte[]{ 0x42, 0x4D }, DecodeBitmap}, 
    { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif }, 
    { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif }, 
    { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng }, 
    { new byte[]{ 0xff, 0xd8 }, DecodeJfif }, 
}; 


public static Size GetDimensions(BinaryReader binaryReader) 
    { 
     int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length; 
     byte[] magicBytes = new byte[maxMagicBytesLength]; 
     for (int i = 0; i < maxMagicBytesLength; i += 1) 
     { 
      magicBytes[i] = binaryReader.ReadByte(); 
      foreach (var kvPair in imageFormatDecoders) 
      { 
       if (magicBytes.StartsWith(kvPair.Key)) 
       { 
        return kvPair.Value(binaryReader); 
       } 
      } 
     } 
     throw new ArgumentException(errorMessage, "binaryReader"); 
    } 
+0

Eh? OrderByDescending調用在.NET 3.5中應該沒有問題......但是爲什麼你會期望移動到2.0來解決問題呢?你期望'byte []。StartsWith'來自哪裏? – 2010-10-08 13:04:07

+0

@oded - 聽起來像一個使用*指令* – 2010-10-08 13:08:01

+0

@Marc失蹤 - 感謝您的校正:) – Oded 2010-10-08 13:19:20

回答

0

此行

int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length; 

只是得到最長的字節數組的長度在你的字典的鍵。因此,只需遍歷imageFormatDecoders中的項目並記錄最長的值,即如下所示(未經測試):

int maxMagicBytesLength = 0; 
foreach (byte[] magicBytes in imageFormatDecoders.Keys) { 
    if (magicBytes.Length > maxMagicBytesLength) 
     maxMagicBytesLength = magicBytes.Length; 
} 
+0

嗨,謝謝你,你是對的,但是我該如何處理byte []。StartsWith在dot net 2.0中? – Ata 2010-10-08 13:16:31

+0

@Ata:將foreach循環移到for循環之外。在foreach循環中,做一個比較第一個'kvPair.Key.Length'項目的循環。 – Heinzi 2010-10-08 13:23:00

0

你是什麼意思的是.NET 3.5不支持OrderByDescending。它的確如此。順便說一下Max(x => x.Length)有什麼問題?

+0

你好,謝謝你,你能解釋一下你想用這個呢? – Ata 2010-10-08 13:06:49

+0

@Ata:'int maxMagicBytesLength = imageFormatDecoders.Keys.Max(x => x.Length)'。 – 2010-10-08 13:08:08

+0

.net是否支持? – Ata 2010-10-08 13:10:59

0

有什麼不對的,在.net 3.5?

Dictionary<int, int> dict = new Dictionary<int, int>(); 
dict[0] = 2; 
dict[1] = 3; 

foreach (var item in dict.OrderByDescending(key => key.Value)) 
{ 
    Console.WriteLine(item.Key); 
    Console.WriteLine(item.Value); 
} 

輸出

2

我懷疑你只是缺乏;

using System.Linq; 

在代碼文件的頂部。不,切換到.net 2在這裏不會有幫助。

+0

這很有道理。 – 2010-10-08 13:16:12