I have got a bad requirement to do; anyway I have to implement that in my application.
I have a Track class
public class Track
{
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
and i have some test data
List<Track> Records = new List<Track>
{
new Track { City = "a", Name = "a", Country = "i" }, // Track 1
new Track { City = "b", Name = "b", Country = "i" }, // Track 2
new Track { City = "a", Name = null, Country = "J" }, // Track 3
new Track { City = "c", Name = "a", Country = "J" }, // Track 4
new Track { City = "b", Name = "a", Country = null}, // Track 5
};
Requirement is i should query the data from Records based on values passed. If any of the property is null then search criteria should ignore that property. It should query based on NonNull properties.
Example:
If i query for City = a, Name = "b", Country = "i" then Result is: Track 1 & Track 3
If i query for City = c, Name = "p", Country = "w" then Result is: Track 4
Name & Country have null values in Track 3 & Track 5.So it will ignore in search. Hope it is clear
I finally land up with below logic
var filterRecords = new List<Track>();
if (!Records.Any(t => string.IsNullOrWhiteSpace(t.City)))
{
filterRecords = Records.Where(c => c.City == _city).ToList(); // Here _city is the method parameter.. assume "a"
}
if (!Records.Any(t => string.IsNullOrWhiteSpace(t.Country)))
{
filterRecords = filterRecords.Where(c => c.City == _country).ToList(); // Here _country is the method parameter.. assume "c"
}
Track class has 12 properties. Checking for 12 times like above is not good sign.
I would like to achieve this by using LINQ or any other which is simple.
Any suggestions please?.
Best solution came to my mind is to build aggregate filter (You can use your Track object for that, because it already has all possible properties for filtering collection, and they are nullable):
This will require only one iteration over collection to define which fields has null. Then simply apply filter to your records: