I have an entity list, where one of the fields (UtcOffset
) is a number.
And I have a filter list offsets
which is a list of numbers.
I want to select with a LINQ from the first list all the entities where the UtcOffset
field is equal or less than to the values from the filter list with the fixed delta
(3600) added.
I have a code that works for "equal-case" only
public class TimeZone
{
public int Id { get; set; }
public string Name { get; set; }
public int UtcOffset { get; set; }
}
var delta = 3600;
List<TimeZone> TimeZones = new List<TimeZone>()
{
new TimeZone() {Id = 1, Name = "America/Tortola", UtcOffset = -14400},
new TimeZone() {Id = 2, Name = "Asia/Kathmandu", UtcOffset = 20700},
new TimeZone() {Id = 3, Name = "Asia/Kolkata", UtcOffset = 19800},
new TimeZone() {Id = 4, Name = "Africa/Tunis", UtcOffset = 3600},
new TimeZone() {Id = 5, Name = "Africa/Windhoek", UtcOffset = 7200},
new TimeZone() {Id = 6, Name = "Europe/Simferopol", UtcOffset = 10800},
}
List<Int32> offsets = new List<Int32>()
{
3600, -10800, -14400
};
var matchedList = TimeZones.Where(t => offsets.Contains(t.UtcOffset)).ToList();
It returns entities with ids 1 and 4.
I want to select entities with ids 1, 4, 5 (which have UtcOffset
less or equal than 3600 + delta
, -10800 + delta
, -14400 + delta
).
How I can modify my LINQ expression to match this case?
If you want it to work more efficiently, just use this (credits to @yawnobleix for spotting this, though it really needs to be Max()
not Min()
):
var matchedList = TimeZones.Where(t => t.UtcOffset <= (offsets.Max() + delta)).ToList();
This way:
class Program
{
static void Main(string[] args)
{
var delta = 3600;
List<TimeZone> TimeZones = new List<TimeZone>()
{
new TimeZone() {Id = 1, Name = "America/Tortola", UtcOffset = -14400},
new TimeZone() {Id = 2, Name = "Asia/Kathmandu", UtcOffset = 20700},
new TimeZone() {Id = 3, Name = "Asia/Kolkata", UtcOffset = 19800},
new TimeZone() {Id = 4, Name = "Africa/Tunis", UtcOffset = 3600},
new TimeZone() {Id = 5, Name = "Africa/Windhoek", UtcOffset = 7200},
new TimeZone() {Id = 6, Name = "Europe/Simferopol", UtcOffset = 10800},
};
List<Int32> offsets = new List<Int32>()
{
3600, -10800, -14400
};
var matchedList = TimeZones.Where(x => offsets.Any(y => x.UtcOffset <= (y + delta))).ToList();
}
}
public class TimeZone
{
public int Id { get; set; }
public string Name { get; set; }
public int UtcOffset { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With