2

I need help with LINQ syntax or methodology, not sure which.

Here's my issue: I have a list of items (Bill, Bob, Ed) and I need to select and filter out anything that the user selected. So if the viewModel contains "Bob", then the LINQ statement should return "Bill","Ed." The trick is that the user can select multiple things, so the viewModel could contain "Ed", "Bob" and so the LINQ statement should return just "Bill."

The viewModel is an IEnumerable and the list of items is a List<>. I have something simple like this as a starting point:

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

where c.Items refers to the Bill, Bob and Ed above. Now I just need to filter out the viewModel selections and I'm struggling with the LINQ syntax. I've tried variations on != viewModel.selectedNames, which led nowhere, some variations using .contains and one using all.

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

I'm currently feeling beached.

2
  • Except? Mar 26, 2012 at 21:25
  • 1
    @StevenJeuris: filteredItems is not the same type as c.Items which precludes Except.
    – user7116
    Mar 26, 2012 at 21:27

1 Answer 1

2

Perhaps something like:

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));

On a second look, perhaps you should restructure your view model slightly:

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); }
    }

    // ...

At this point you'd do your wiring up in the view:

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

In your view model's constructor you'd apply the appropriate eventing to ensure that ValidPeople got updated when needed:

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"); };
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.