Reputation: 88187
This is my setup
class EditorTabViewModel : TabViewModel {
...
public bool CanSave { get; set; };
}
ObservableCollection<TabViewModel> _tabs
I want to check if there are any tabs in _tabs
that are EditorTabViewModel
that has property CanSave
set to true
i did something like ...
var tabs = from t in _tabs
where t is EditorTabViewModel
&& ((EditorTabViewModel)t).CanSave == true
select t;
if (tabs.Count() > 0)
return true;
else
return false;
I wonder if there is a better way to do this? maybe i won't need to retrieve all tabs, or maybe I just need to query the count or something?
Upvotes: 3
Views: 144
Reputation: 23462
Try something like:
return _tabs.FirstOrDefault(y => y is EditorTabViewModel && ((EditorViewModel)t).CanSave) != null;
Upvotes: 1
Reputation: 3987
Yes, you can improve. Something like this would probably work:
return _tabs.Any(x => x is EditorTabViewModel && ((EditorTabViewModel)x).CanSave);
Upvotes: 2
Reputation: 1062520
How about:
return _tabs.OfType<EditorTabViewModel>().Any(t => t.CanSave);
Here:
OfType<>
is a non-buffering filter that restricts us to EditorTabViewModel
Any
is short-circuiting, so returns true as soon as a match is foundUpvotes: 11
Reputation: 7823
Using the linq extensions you could write something like
_tabs.Any( p => p is EditorTabViewModel && ((EditorTabViewModel)t).CanSave)
Upvotes: 1