1

我试图通过查看元组列表中同一元组中另一个项目的值来获取一个项目的值。我最终需要做的是获取所有具有特定 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));
4

2 回答 2

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);
于 2013-06-20T17:49:13.327 回答
2

这是一个相当简单的 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,您将更加精通操作集合。

于 2013-06-20T17:41:03.310 回答