【问题标题】:How do I grab a value of an item in a List of Tuples based off of a value from another item?如何根据另一个项目的值获取元组列表中项目的值?
【发布时间】:2013-06-20 17:35:09
【问题描述】:

我试图通过查看元组列表中同一元组中另一个项目的值来获取一个项目的值。我最终需要做的是获取所有具有特定 Item2 的元组,从该选择中选择最近的 DateTime 并获取 Item1。

因此,例如,如果我想最终从“程序员”组中获取最新的名称,我希望逻辑会获取所有显示“程序员”的 Item2,查看哪个具有最新的日期并输出“ Stan”,因为 6/25 比 6/20 更新。

    List<Tuple<string, string, DateTime>> myList;
    myList.Add(new Tuple<string, string, DateTime>("Bob", "Programmer", 6/20/2013));
    myList.Add(new Tuple<string, string, DateTime>("Stan", "Programmer", 6/25/2012));
    myList.Add(new Tuple<string, string, DateTime>("Curly", "Athlete", 6/20/2013));

【问题讨论】:

    标签: c# list tuples


    【解决方案1】:

    这是一个相当简单的 LINQ 操作。第一步是按 DateTime (Item3) 对列表进行排序,之后您可以在查询上链接First(),它将返回最新的项目。请注意,LINQ 操作未就地完成,这意味着 myList 中的项目顺序不会受到此操作的影响。它将创建一个新的IEnumerable,由tuple.Item3 订购,然后给你第一个项目。

    Tuple<string, string, DateTime> mostRecent = myList.Orderby(x => x.Item3).First();
    

    要添加对组的限制,您只需添加一个 where 子句。

    Tuple<string, string, DateTime> mostRecent = myList.Where(y => y.Item2 == "Programmer").Orderby(x => x.Item3).First();
    

    我建议您查看有关 LINQ to Objects 查询运算符的文档。我使用的所有内容都是标准查询运算符,您可能会在现代 C# 代码库中到处看到它们。如果您了解如何使用标准查询运算符,例如 Select、Where、OrderBy、ThenBy 以及可能是 Join 和 SelectMany,您将更加精通操作集合。

    【讨论】:

    • 我明白你的意思,但在某些情况下,我不关心的另一个组中的 DateTime 可能高于我正在查看的组中的那些。那么这段代码不会仍然按所有日期时间排序吗? (所以如果 Curly 的 DateTime 是 2013 年 7 月 15 日,那会在 Bob 和 Stan 的 DateTimes 之前吗?)
    • @Zldamstr 你可以修改它以获得你想要的任何结果。我将添加另一个查询以仅从“程序员”组中获取项目。
    • 太棒了!我只需要将其更改为 OrderByDescending 即可满足我的需求。非常感谢!
    【解决方案2】:
    List<Tuple<string, string, DateTime>> myList = new List<Tuple<string,string,DateTime>>();
    
    myList.Add(new Tuple<string, string, DateTime>("Bob", "Programmer", new DateTime(2013,6,20)));
    myList.Add(new Tuple<string, string, DateTime>("Stan", "Programmer", new DateTime(2013, 6, 25)));
    myList.Add(new Tuple<string, string, DateTime>("Curly", "Athlete", new DateTime(2013, 6, 20)));
    
    var result = myList.Where(x => x.Item2.Equals("Programmer")).OrderByDescending(x => x.Item3).Take(1);
    

    【讨论】:

    • 谢谢!我理解 .Where 之后的部分,但你能解释一下为什么 .AsEnumerable() 是必要的吗?
    • 在这种情况下没有必要。最近我一直在使用 DataTable 对象并使用 AsEnumerable() 因为在这种情况下我需要它以便能够对其执行 LINQ 操作,如您在此处看到的:msdn.microsoft.com/en-us/library/…
    猜你喜欢
    • 1970-01-01
    • 2020-07-10
    • 2016-03-12
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    相关资源
    最近更新 更多