For C #, these two options achieve what you want, but I would not put this into my software quickly. I also doubt that this is becoming more readable or more understandable. There is another option, but this requires reorganizing the model class chain. If you implement NullObject for the Bids type and the Item type, you can do if(Model.Bids.Items.Count > 0) because all types will not be null, but has an implementation that handles an empty state (like String.Empty)
assistants
bool tc(Func<bool> comp ) { try { return comp.Invoke(); } catch (Exception) { return false; } } T1 f1<T,T1>(T root, Func<T, T1> p1) where T:class { T1 res = default(T1); if (root != null) { res = p1.Invoke(root); } return res; } bool f<T,T1,T2,TL>( T root, Func<T,T1> p1, Func<T1,T2> p2, Func<T2,TL> plast, Func<TL, bool> comp) where T:class where T1:class where T2:class { var allbutLast = f1(f1(root, p1), p2); return allbutLast != null && comp(plast.Invoke(allbutLast)); }
Using
var m = new Model(); if (f(m, p => p.Bids, p => p.Items, p => p.Count, p => p > 0)) { Debug.WriteLine("f"); } if (tc(() => m.Bids.Items.Count > 0)) { Debug.WriteLine("tc "); } if (m.Bids != null && m.Bids.Items != null && m.Bids.Items.Count > 0) { Debug.WriteLine("plain"); }
rene
source share