C # / LINQ: an attempt to optimize performance

This is my setting

class EditorTabViewModel : TabViewModel {
    ...
    public bool CanSave { get; set; };
}

ObservableCollection<TabViewModel> _tabs

I want to check if there are any tabs in _tabswhich EditorTabViewModelwhich property is CanSaveset 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 don’t need to retrieve all the tabs, or maybe I just need to request an invoice or something else?

+3
source share
4 answers

What about:

return _tabs.OfType<EditorTabViewModel>().Any(t => t.CanSave);

Here:

  • OfType<> is a non-buffered filter that limits us EditorTabViewModel
  • Any is short-circuited, so returns true as soon as a match is found
+11
source

Yes, you can improve. Maybe something like this:

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

Using linq extensions you can write something like

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

+1
source

Try something like:

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

Source: https://habr.com/ru/post/1770290/


All Articles