Jiew Meng
Jiew Meng

Reputation: 88187

C#/LINQ: Trying to optimize performance

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

Answers (4)

Tomas Jansson
Tomas Jansson

Reputation: 23462

Try something like:

return _tabs.FirstOrDefault(y => y is EditorTabViewModel && ((EditorViewModel)t).CanSave) != null;

Upvotes: 1

Onkelborg
Onkelborg

Reputation: 3987

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

return _tabs.Any(x => x is EditorTabViewModel && ((EditorTabViewModel)x).CanSave);

Upvotes: 2

Marc Gravell
Marc Gravell

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 found

Upvotes: 11

Zephyr
Zephyr

Reputation: 7823

Using the linq extensions you could write something like

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

Upvotes: 1

Related Questions