2010-10-08 70 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