[英]LINQ Query with multiple conditions and setting values into a list
Im working on a project at the moment which I am working with xml c# and line queries. 我目前正在处理xml c#和行查询的项目。
The main aim of this functions is to create A list of dates, with the total distance covered on each date (across all drivers), sorted by date (note that dates are formatted as YYYY/MM/YY to make sorting easier) 此功能的主要目的是创建一个日期列表,其中每个日期(所有驱动程序)涵盖的总距离按日期排序(请注意,日期格式为YYYY / MM / YY以便于排序)
The only part I am unsure about is the last part where I'm sorting by date as I can only sort by distance at the moment. 我不确定的唯一部分是我按日期排序的最后一部分,因为目前我只能按距离排序。
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
};
Tried to answer your question and tweaked code little bit to achieve the same result. 试图回答您的问题,并稍微调整了代码以达到相同的结果。
Mock Models 模拟模型
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; }
}
Here is the function created in console app, just remove test code and fill it with your data. 这是在控制台应用程序中创建的功能,只需删除测试代码并将其填充数据即可。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.