Having some trouble with Predicates in C#.
I have two sets of code (Both of which I believe should accomplish the same result) but one never works. The reason I am asking is I need this predicate to appear a few times with different elements and so I’d like to keep it as minimal as possible (the non working one is very simplistic while the other contains many lines).
1 Not working:
ItemViewModel item = (App.ViewModel.All_Items.Where(x => (x as ItemViewModel).Name == my_list_of_strings.ElementAt(2)) as ItemViewModel);
Also using "Select" instead of Where isn’t working.
2 Working:
foreach (ItemViewModel it in App.ViewModel.All_Items)
{
if (item.Name == my_list_of_strings.ElementAt(2))
{
MessageBox.Show("Success!!");
item = it;
continue; // Leave loop
}
}
It’s probably something stupid that I’ve overlooked but if anyone knows the solution, that would be great!
Thanks.
IEnumerable<T>.Where(Func<T, bool>)returns a collection however it looks like what you want is a single element. There are a couple of options:In your example it would be: