从 viewModel 和 List<> 进行 LINQ 过滤

标签 linq c#-4.0

我需要有关 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/

相关文章:

asp.net - 在 SQL Server 2008 中启用 Service Broker

c#-4.0 - 对列进行排序,同时通过 Entity Framework 4.1 创建 DB。使用流畅的 API

C#:具有两个构造函数的对象:如何限制将哪些属性设置在一起?

c# - C# 4.0 中的类属性/字段可以是匿名类型吗?

c# - 使用 LINQ 查询初始化 List<int>

c# - 是否可以在 C#/LINQ 中扩展查询关键字?

c# - 如何在XElement属性上使用LINQ Group by

linq - CompiledQuery 与 List.Contains (where...in list) 功能?

c# - 动态 COM 对象是否被视为托管资源?

.net - .NET 中的别名