我有一个不好的要求要做;无论如何,我必须在我的应用程序中实现它。
我有一Track
堂课
public class Track
{
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
我有一些测试数据
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
};
要求是我应该Records
根据传递的值查询数据。如果有任何属性,null
则搜索条件应忽略该属性。它应该根据NonNull
属性进行查询。
示例:
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
值。所以它会在搜索中忽略。希望清楚Track 3
Track 5
我终于明白了以下逻辑
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
类有 12 个属性。像上面那样检查 12 次不是好兆头。我想通过使用LINQ
或任何其他简单的方法来实现这一点。
请问有什么建议吗?