2014-10-09 56 views
0

假設您有List<Image>,則使用類似的方法添加解決方案資源中找到的所有圖像;按名稱對從資源加載的圖像列表進行排序

using (ResourceSet resourceSet = SomeProject.Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true)) 
     { 
      foreach (DictionaryEntry entry in resourceSet) 
      { 
       SomeList.Add((Image)entry.Value); 
      } 
     } 

在這種情況下,我們的資源中會有三張圖片。 Apple.png Banana.png, Cactus.png

如何按字母順序排列此列表,以便我可以按正確的順序循環訪問,得到Apple -> Banana -> Cactus

我讀過How to sort ResourceSet in C#,我試圖應用於我的情況,但無濟於事。

通過我自己,我已經試過分配entry.Key到圖像的標籤,然後做someList.OrderBy(f => f.Tag).ToList();

下面是我用它來測試這個

List<Image> someList = new List<Image>(); 

    private void button1_Click(object sender, EventArgs e) 
    { 
     using (ResourceSet resourceSet = WindowsFormsApplication52.Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true)) 
     { 
      foreach (DictionaryEntry entry in resourceSet) 
      { 
       Image i = (Image)entry.Value; 
       i.Tag = entry.Key; 
       someList.Add((Image)i); 
      } 

      someList.OrderBy(f => f.Tag).ToList(); 
     } 

     foreach(var x in someList) 
     { 
      PictureBox pb = new PictureBox(); 
      pb.Image = x; 
      pb.Size = new System.Drawing.Size(200, 200); 
      pb.SizeMode = PictureBoxSizeMode.Zoom; 
      flowLayoutPanel1.Controls.Add(pb); 
     } 
    } 

這是結果的完整代碼,我似乎得到每時間, http://puu.sh/c5BTz/41f828cf1b.jpg

我不知道它是否考慮到文件大小,但在這種情況下,圖像的文件大小也是按順序。 (Apple.png是最大的,仙人掌是最小的)。

幫助是極大的讚賞。

+1

您可以使用排序字典爲您排序。只需將名稱作爲密鑰添加到它的所有文件。然後做一個foreach循環來按字母順序檢索所有內容。 – deathismyfriend 2014-10-09 16:08:06

+0

您是否看過每個項目上的Tag屬性的值,並確認它們正確地命名爲Apple,Banana和Cactus? – 2014-10-09 16:11:06

+0

@deathismyfriend我甚至不知道它的存在,我改變了我的列表到一個有序的字典,如你所說,並且..它已經排序!非常感謝你。如果可能,我會將您的評論標記爲答案。 Dave Zych是的,我做了,標籤設置正確。 – Stella 2014-10-09 16:17:24

回答

1

您可以將所有圖像添加到排序字典中,圖像名稱爲鍵。 然後你在字典上做一個foreach,按照名稱的字母順序檢索圖像。