2011-01-29 111 views
1

我有一列有許多列的行。說,一首歌是一排,專輯,藝術家,標題,年份是它的專欄。這些顯示在列表視圖中。當我多選5首歌曲時,我需要檢查一下所有5首歌曲是否相同。專輯,標題,年份也一樣。如何比較列表的列值

我的僞代碼如下:

ListView.SelectedListViewItemCollection selectedItem = this.lvuFiles.SelectedItems; 

foreach (ListViewItem itemSelected in selectedItem) 
{ 
    // pass a list of 'title's to a method to check for equality 
} 

我已經實現,其檢查是否相等的方法。我只是無法弄清楚如何存儲列表(標題列表,專輯列表等)並傳遞它們。

編輯:

Screenshot of List View http://i.min.us/iexmSg.png

現在,我需要檢查3個標題都符合。我認爲的一種方式是將所有標題添加到列表中並傳遞給方法。對藝術家,專輯也一樣。我無法獲得selectedItems的值。所以,我必須爲多個屬性維護多個列表。有沒有更好的方法。至於給出的建議,我嘗試了linq之一。說,方法沒有定義。

回答

0

您可以使用linq功能集運算符'All'。

using System.Linq; 
... 
var title = selectedItems.First().Column["Title"].Value; 
var sameTitle = selectedItems.All(i => i.Column["Title"].Value == title); 
// repeat for artist, album, year, etc. 

我不知道如何得到一個值的確切語法,但希望你可以翻譯它。我認爲關鍵是要注意,你實質上要求的是「所有的價值都是一樣的」。鏈接是你的朋友進行這樣的設置操作。

1

有沒有更好的辦法。

絕對。對於初學者來說,LINQ的建議是完美的;唯一的問題是ListView.SelectedItems屬性的類型沒有實現IEnumerable<ListViewItem>;我是猜測這就是爲什麼它不適合你。你可以用一個簡單的Cast<T>呼叫解決這個問題:現在

if (listView.SelectedItems.Count > 0) 
{ 
    var titles = from x in listView.SelectedItems.Cast<ListViewItem>() 
       select x.SubItems[titleColumn.Index].Text; 

    string firstTitle = titles.First(); 
    bool allSameTitle = titles.All(t => t == firstTitle); 
} 

,如果真正原因LINQ建議沒有爲你工作是,你被困在.NET 2.0,不要害怕。你仍然可以泛化這種行爲。定義一種方法來查看IEnumerable中的每個項目,並根據某個選擇器函數確定它們是否都符合給定條件。這裏有一個如何做到這一點的例子:

public static bool All(IEnumerable source, Predicate<object> criterion) 
{ 
    foreach (object item in source) 
    { 
     if (!criterion(item)) 
     { 
      return false; 
     } 
    } 

    return true; 
} 

那麼你會調用這個方法,這樣你的ListView.SelectedItems

if (listView.SelectedItems.Count > 0) 
{ 
    string firstTitle = listView.SelectedItems[0].SubItems[titleColumn.Index].Text; 

    Predicate<object> sameTitle = delegate(object obj) 
    { 
     if (!(obj is ListViewItem)) 
     { 
      return false; 
     } 

     return ((ListViewItem)obj).SubItems[titleColumn.Index].Text == firstTitle; 
    }; 

    bool allSameTitle = All(listView.SelectedItems, sameTitle); 
}