如何筛选列表<;对象>;以获取基于给定字段的最新值

本文关键字:获取 最新 字段 对象 何筛选 筛选 lt 列表 gt | 更新日期: 2023-09-27 18:23:44

我有一个Issue类的对象列表。每个对象都有一个日期戳和一个Boolean,用于确定问题是否仍处于活动状态。对于给定的Issue ID(指其他地方的另一个集合),可能有多个条目为true或false,我只关心最新的true值。

从这个列表中,我需要获得最新值为true的项目的所有id的列表。我以一种看似疯狂而低效的方式实现了这一点。我认为必须有一种更精简的方法:

class Program
{
    static void Main(string[] args)
    {
        var IssueList = new List<Issue>();
        // Add four Issues
        IssueList.Add(new Issue() { labelId = "1", Result = false, AuditDate = DateTime.Now.AddHours(-1), Note = "No: Latest, but false" });
        IssueList.Add(new Issue() { labelId = "1", Result = true, AuditDate = DateTime.Now.AddHours(-6), Note = "No: Superceeded" });
        IssueList.Add(new Issue() { labelId = "1", Result = false, AuditDate = DateTime.Now.AddHours(-5), Note = "No: Superceeded" });
        IssueList.Add(new Issue() { labelId = "2", Result = true, AuditDate = DateTime.Now.AddHours(-6), Note = "Yes: Latest and True" });
        // Get the unique ids
        var ids = (from id in IssueList.OfType<Issue>()
                   select id.labelId).Distinct();
        // Process each id in a loop and get the latest Issue for each id
        List<Issue> latestList = new List<Issue>();
        foreach (string id in ids)
        {
            // Get a new collection with the most recent Issue for each id
            List<Issue> idFiltered = IssueList.Where(i => i.labelId == id).ToList().OrderBy(o => o.AuditDate).ToList();
            latestList.Add(idFiltered.LastOrDefault());
        }
        // Get just the True values
        List<Issue> trueList = latestList.Where(r => r.Result == true).ToList();
        // Get the Ids (Distinct should be redudant here)
        List<string> theIds = (from id in trueList.OfType<Issue>()
                               select id.labelId).Distinct().ToList();
        Console.WriteLine("Press ENTER to quit");
        Console.ReadLine();
    }
    private class Issue
    {
        public Issue() { }
        public string labelId { get; set; }
        public bool Result { get; set; }
        public DateTime AuditDate { get; set; }
        public string Note { get; set; }
    }
}

列表正确地只返回id 2,但我认为一定有更好的方法。

如何筛选列表<;对象>;以获取基于给定字段的最新值

var trueIdList = IssueList.OfType<Issue>()
           .GroupBy(c => c.labelId)
           .Select(c => c.OrderBy(o => o.AuditDate).LastOrDefault())
           .Where(c => c.Result)
           .Select(c => c.labelId)
           .ToList();

这是一个分为两部分的问题。

首先,从项目组中查找最新项目,按ID:分组

var latest = 
    from issue in IssueList.OfType<Issue>()
    group issue by issue.labelId into grp
    select grp.OrderByDescending(g => g.AuditDate).FirstOrDefault();

然后隔离具有Result成员集的项目列表:

var ids = 
    from issue in latest 
    where issue.Result 
    select issue.labelId;

从功能上讲,这相当于chsword的答案,但我认为分两部分来强调它的功能会稍微清晰一些。