Hello, I ran into a problem, my code looks somehow cumbersome. Because of the condition by which I want to select records from a specific table. I have a table, I do a selection of 2 string fields (EventName, VenueName). There are also some input data (the names for which I search, let's say at the input EN = 'MyEvent' and VN = 'MyVenue') I need to select the records where

EventName == EN & VenueName == VN + must be added to the sample record, where

EventName == EN & VenueName == null or

EventName == null & VenueName == VN. Those. just write

EventName == EN | VenueName == VN EventName == EN | VenueName == VN fail. Is it possible to somehow better write this expression easier than mine?

 dynamicNotes = dynamicNotes.Where( x => ((x.VenueName.Equals(searchModel.VenueName)) && (x.EventName.Equals(searchModel.EventName))) || (x.VenueName.Equals(searchModel.VenueName)) && (string.IsNullOrEmpty(x.EventName)) || (x.EventName.Equals(searchModel.EventName)) && (string.IsNullOrEmpty(x.VenueName))); 
  • And this is not your outer join by chance? - VladD
  • @VladD I think not, I need to get all the records, except those where in one EventName and VenueName are not suitable for the first condition - simply good
  • those. if on the course EN = 'e' and VN = 'n', under my condition, I got the writing 1) EN = 'e', ​​VN = 'n' 2) EN = 'e', ​​VN = null 3) EN = null, VN = 'n' but the EN = 'e' record does not work, VN = 'something' or EN = 'something', VN = 'n' - simply good
  • Judging by the code, you call Equals on properties that can be null . - Alexander Petrov

1 answer 1

You can make a list of predicates in advance; in general, this will not reduce the amount of code, but it can make understanding easier, because each filter will have a meaningful name.

 Func<dynamicNote, bool> fullMath = (x) => x.VenueName.Equals(searchModel.VenueName) && x.EventName.Equals(searchModel.EventName); Func<dynamicNote, bool> onlyVenueName = (x) => x.VenueName.Equals(searchModel.VenueName) && string.IsNullOrEmpty(x.EventName); Func<dynamicNote, bool> onlyEventName = (x) => x.EventName.Equals(searchModel.EventName) && string.IsNullOrEmpty(x.VenueName); Func<dynamicNote, bool> allRules = (x) => fullMath(x) || onlyVenueName(x) || onlyEventName(x); dynamicNotes = dynamicNotes.Where(allRules);