简体   繁体   中英

LINQ: Filter the list according to the math condition above elements in another list

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?

如果您希望它更有效地工作,只需使用它(@yawnobleix的信用点就可以发现它,尽管它实际上需要是Max()而不是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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM