如何将具有相同最大日期的列表中的项目分组并过滤它们

How to group items in a list with the same max date and filter them

我有 List<TakenBMI> 这 4 列和数据:

TakenDate     UerID   TakenItem   TakenValue
Aug-10-2014     34     Weight       140
Aug-10-2014     34     Height       5.5
Mar-15-2015     34     Weight       141
Mar-15-2015     34     Height       5.5

我想根据 TakenDate 将它们分组到单独的列表中,并找出我应该使用哪个列表,其中包含最新拍摄日期的详细信息。

这是我尝试过的方法:

var q = from n in TakenBMI 
        group n by n.TakenDate into g 
        select g.OrderByDescending(t=>t.TakenDate )
                .FirstOrDefault(); 

var m = from n in TakenBMI 
        group n by n.TakenDate into g 
        select new { TakenDate = Convert.ToDateTime(q) };

此外,如果有人在获得具有最大日期的列表后可以提出建议,如果可能的话,我如何获得第二个最新日期的列表?谢谢大家回复

我一般用字典

   class Program
    {
        static void Main(string[] args)
        {
            List<TakenBMI> data = new List<TakenBMI>() {
               new TakenBMI() {TakenDate = DateTime.Parse("Aug-10-2014"), UerID = 34,  TakenItem = "Weight", TakenValue = 140},
               new TakenBMI() {TakenDate = DateTime.Parse("Aug-10-2014"), UerID = 34,  TakenItem = "Height", TakenValue = 5.5},
               new TakenBMI() {TakenDate = DateTime.Parse("Aug-15-2014"), UerID = 34,  TakenItem = "Weight", TakenValue = 141},
               new TakenBMI() {TakenDate = DateTime.Parse("Aug-15-2014"), UerID = 34,  TakenItem = "Height", TakenValue = 5.5},
            };

            Dictionary<DateTime, List<TakenBMI>> dict = data.AsEnumerable()
                .GroupBy(x => x.TakenDate, y => y)
                .ToDictionary(x => x.Key, y => y.ToList());

        }
    }
    public class TakenBMI
    {
        public DateTime TakenDate {get;set;}
        public int UerID {get;set;}
        public string TakenItem {get;set;}
        public double TakenValue {get;set;} 
    }
}

我会找到最晚的日期:

var latestDate = items.Select(i => i.TakenDate).Max();

然后过滤具有该日期的项目:

var itemsWithLatestDate = items.Where(i => i.TakenDate == latestDate).ToList();

如果您要求所有这些按日期顺序分组,则:

var itemsByDate = items.GroupBy(i => i.TakenDate).OrderBy(g => g.Key);

最新的日期组将是这些组中的最后一个:

var itemsWithLatestDate = itemsByDate.Last();

I want to group them in separate lists based on the TakenDate

您可以 group by TakenDate 使用 GroupBy() LINQ 查询运算符并枚举结果如下:

var groups = TakenBMIList.GroupBy(x => x.TakenDate);

foreach (var group in groups)
{
    Console.WriteLine("TakenDate: {0}", group.Key);

    List<TakenBMI> list = group.ToList(); //List of TakenBMI with current TakenDate
}

find out which list I should use that has details with the latest taken date

您可以找到 slatest (max) TakenDate 如下:

var latestTakenBMIs = TakenBMIList.Where(x => x.TakenDate == TakenBMIList.Max(y => y.TakenDate)).ToList();