tags:

views:

62

answers:

4

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?

+1  A: 

Using the linq extensions you could write something like

_tabs.Any( p => p is EditorTabViewModel && ((EditorTabViewModel)t).CanSave)

Noel Abrahams
+11  A: 

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 found
Marc Gravell
+1 for better answer than me... because I guess it works :).
mastoj
wow, short and simple, I like it
jiewmeng
+1  A: 

Try something like:

return _tabs.FirstOrDefault(y => y is EditorTabViewModel && ((EditorViewModel)t).CanSave) != null;
mastoj
`SingleOrDefault` must still consume the entire sequence, to ensure that there aren't *two* matches. Indeed, this will have a different outcome (an exception) to the original code (which would return true) when there are multiple tabs that can be saved.
Marc Gravell
@Marc: I meant to use `FirstOrDefault` of course :).
mastoj
+2  A: 

Yes, you can improve. Something like this would probably work:

return _tabs.Any(x => x is EditorTabViewModel && ((EditorTabViewModel)x).CanSave);
Onkelborg
Haha, lot's of duplicates :)
Onkelborg