LINQ查询具有多个条件并将值设置到列表中

时间:2018-05-04 00:07:50

标签: c# xml linq

我正在处理一个项目,我正在使用xml c#和行查询。

此功能的主要目的是创建一个日期列表,每个日期(所有驱动程序)覆盖的总距离,按日期排序(请注意,日期格式为YYYY / MM / YY,以便更容易排序)

我不确定的唯一部分是我按日期排序的最后一部分,因为我现在只能按距离排序。

public List<String> CalculateDistDates()
    {
        List<String> distDatesList = new List<string>();

        var datesDistTot =
            from Driver in this.Drivers
            from Journey in Driver.Journeys
            group Journey by Journey.JourneyDate into distance
            let totaldistance = (from jour in distance
            select (int)jour.Distance).Sum() 
            orderby totaldistance descending


            select new
            {
                journeyDate = .Key,
                totaldistance = totaldistance

            };

1 个答案:

答案 0 :(得分:0)

试图回答你的问题并稍微调整一下代码以达到相同的效果。

模拟模型

 public class Journey
    {
        public decimal Distance { get; set; }
        public DateTime JourneyDate { get; set; }
    }
    public class Drivers
    {
        public string Name { get; set; }
        public Journey Journey { get; set; }
    }

    public class  DistanceCovered
    {
        public DateTime JourneyDate { get; set; }
        public decimal TotalDistance { get; set; }
    }

以下是在控制台应用中创建的功能,只需删除测试代码并将其填入您的数据。

public static void CalculateDistDates()
    {            
        var drivers = new List<Drivers>
        {
            new Drivers{Journey = new Journey {Distance = 1.2M, JourneyDate = DateTime.Now.AddDays(1).Date}},
            new Drivers{Journey =  new Journey{Distance = 1.2M, JourneyDate = DateTime.Now.AddDays(2).Date}},
            new Drivers{Journey =  new Journey{Distance = 1.1M, JourneyDate = DateTime.Now.AddDays(2).Date}},
            new Drivers{Journey =  new Journey{Distance = 1.5M, JourneyDate = DateTime.Now.AddDays(3).Date}},
            new Drivers{Journey = new Journey {Distance = 1.7M, JourneyDate = DateTime.Now.AddDays(-1).Date}},
            new Drivers{Journey =  new Journey{Distance = 1.1M, JourneyDate = DateTime.Now.AddDays(3).Date}},
            new Drivers{Journey =  new Journey{Distance = 0.2M, JourneyDate = DateTime.Now.AddDays(2).Date}}
        };

        var totalDistance = (from d in drivers
            group d by d.Journey.JourneyDate
            into j                 
            select new DistanceCovered
            {
                JourneyDate = j.Key,
                TotalDistance = j.Sum(r=>r.Journey.Distance)
            }).ToList().OrderBy(r=>r.JourneyDate).ThenByDescending(r=>r.TotalDistance);

        foreach (var t in totalDistance)
        {
            Console.WriteLine($"{t.JourneyDate}: {t.TotalDistance}" );
        }

        Console.ReadLine();            
    }
相关问题