我需要有关 LINQ 语法或方法的帮助,但不确定是哪一个。
这是我的问题:我有一个项目列表(Bill、Bob、Ed),我需要选择并过滤掉用户选择的任何内容。因此,如果 viewModel 包含“Bob”,则 LINQ 语句应返回“Bill”、“Ed”。诀窍在于用户可以选择多个内容,因此 viewModel 可以包含“Ed”、“Bob”,因此 LINQ 语句应该只返回“Bill”。
viewModel 是一个 IEnumerable,项目列表是一个 List<>。我有这样简单的东西作为起点:
c.Items.select(p=>p.Name)
其中 c.Items 指的是上面的 Bill、Bob 和 Ed。现在我只需要过滤掉 viewModel 选择,并且我正在努力使用 LINQ 语法。我尝试过 != viewModel.selectedNames 的变体,但没有任何结果,一些变体使用 .contains ,一种使用 all 。
var filteredItems = viewModel.selectedNames;
c.Items.Where(p => filteredItems.All(t => !p.Name.Contains(t)));
我现在感觉自己被搁浅了。
最佳答案
也许是这样的:
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));
再看一遍,也许您应该稍微重组您的 View 模型:
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); }
}
// ...
此时,您将在 View 中进行接线:
<ListBox ItemSource="{Binding AllPeople}"
SelectedItems="{Binding SelectedPeople}" />
<ItemsControl ItemsSource="{Binding ValidPeople}" />
在 View 模型的构造函数中,您将应用适当的事件以确保 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"); };
}
关于从 viewModel 和 List<> 进行 LINQ 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9880073/