开发者

C#/LINQ: Trying to optimize performance

开发者 https://www.devze.com 2023-01-20 22:40 出处:网络
This is my setup class EditorTabViewModel : TabViewModel { ... public bool CanSave { get; set; }; } ObservableCollection<TabViewModel> _tabs

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
    开发者_Python百科        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?


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


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

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


Using the linq extensions you could write something like

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


Try something like:

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

精彩评论

暂无评论...
验证码 换一张
取 消