2012-03-26 26 views
2

我需要LINQ語法或方法的幫助,不知道哪個。從視圖模型和列表LINQ過濾<>

這是我的問題:我有一個項目列表(比爾,鮑勃,埃德),我需要選擇和篩選出用戶選擇的任何東西。所以如果viewModel包含「Bob」,那麼LINQ語句應該返回「Bill」,「Ed」。訣竅是用戶可以選擇多個東西,因此viewModel可以包含「Ed」,「Bob」,因此LINQ語句應該只返回「Bill」。

viewModel是IEnumerable,項目列表是列表<>。我有這樣一個簡單的起點:

c.Items.select(p=>p.Name) 

其中c.Items是指比爾,鮑勃和埃德上面。現在我只需要過濾出viewModel選擇,並且我正在努力使用LINQ語法。我已經嘗試了!= viewModel.selectedNames的變體,這導致了無處不在,使用.contains和使用全部變體的一些變體。

var filteredItems = viewModel.selectedNames; 
c.Items.Where(p => filteredItems.All(t => !p.Name.Contains(t))); 

我現在感覺被擱淺了。

+0

[除外](http://msdn.microsoft.com/en-us/library/system。 linq.enumerable.except.aspx)? – 2012-03-26 21:25:27

+1

@StevenJeuris:'filteredItems'與「c.Items」不同,它排除了'Except'。 – user7116 2012-03-26 21:27:04

回答

2

也許是這樣的:

var filteredNames = new HashSet<string>(viewModel.SelectedNames); 

// nb: this is not strictly the same as your example code, 
// but perhaps what you intended  
c.Items.Where(p => !filteredNames.Contains(p.Name)); 

在第二次看,也許你應該稍微調整你的視圖模型:

public class PeopleViewModel : ViewModelBaseOfYourLiking 
{ 
    public ObservableCollection<Person> AllPeople 
    { 
     get; 
     private set; 
    } 

    public ObservableCollection<Person> SelectedPeople 
    { 
     get; 
     private set; 
    } 

    public IEnumerable<Person> ValidPeople 
    { 
     get { return this.AllPeople.Except(this.SelectedPeople); } 
    } 

    // ... 

在這一點上,你會做你的接線,在查看:

<ListBox ItemSource="{Binding AllPeople}" 
     SelectedItems="{Binding SelectedPeople}" /> 
<ItemsControl ItemsSource="{Binding ValidPeople}" /> 

在您的視圖模型的構造你會應用適當的三項賽,以保證在需要的時候得到了ValidPeople更新:

public PeopleViewModel(IEnumerable<Person> people) 
{ 
    this.AllPeople = new ObservableCollection<Person>(people); 
    this.SelectedPeople = new ObservableCollection<Person>(); 

    // wire up events to track ValidPeople (optionally do the same to AllPeople) 
    this.SelectedPeople.CollectionChanged 
     += (sender,e) => { this.RaisePropertyChanged("ValidPeople"); }; 
}