我试图通过查看元组列表中同一元组中另一项的值来获取该项的值。我最终需要做的是获取所有具有特定Item2的元组,从该选择中选择最新的DateTime并获取Item1。
因此,例如,如果我想最终从“程序员组”中获取最近的名字,我会期望逻辑获取所有说“程序员”的Item2s,看看哪一个拥有最新的日期,并输出"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));发布于 2013-06-21 01:41:03
这是一个使用LINQ的相当简单的操作。第一步是按DateTime (Item3)对列表进行排序,之后您可以在查询上链接First(),它将返回最新的项。请注意,LINQ操作没有就地完成,这意味着myList中的项的顺序不会受到此操作的影响。它将创建一个按tuple.Item3排序新IEnumerable,然后为您提供其中的第一项。
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-21 01:49:13
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);https://stackoverflow.com/questions/17220150
复制相似问题