I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this:
我有一个元组列表,其中每个元组由两个整数组成,我想按第二个整数排序。在看了python的帮助之后,我得到了这个:
sorted(myList, key=lambda x: x[1])
which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the obvious answer involving creating classes and specifying an anonymous delegate for the whole compare step but perhaps there is a linq oriented way as well. Thanks in advance for any suggestions.
这是伟大的。我的问题是,在c#(我必须使用的语言)中,是否有同样简洁的方法来实现这一点?我知道关于创建类和为整个比较步骤指定匿名委托的明显答案,但是也许还有一种面向linq的方法。谢谢你的建议。
2 个解决方案
#1
6
Assuming that the list of tuples has a type IEnumerable<Tuple<int, int>>
(a sequence of tuples represented using Tuple<..>
class from .NET 4.0), you can write the following using LINQ extension methods:
假设元组列表具有类型IEnumerable
var result = myList.OrderBy(k => k.Item2);
In the code k.Item2
returns the second component of the tuple - in C#, this is a property (because accessing item by index wouldn't be type-safe in general). Otherwise, I think that the code is pretty succinct (also thanks to nice lambda function notation).
在代码中k。Item2返回元组的第二个组件——在c#中,这是一个属性(因为按索引访问项通常不会是类型安全的)。否则,我认为代码非常简洁(也要感谢lambda函数符号)。
Using the LINQ query syntax, you could write it like this (although the first version is IMHO more readable and definitely more succinct):
使用LINQ查询语法,您可以这样编写(尽管第一个版本更易于阅读,而且绝对更简洁):
var result = from k in myList orderby k.Item2 select k;
#2
14
Another way to do it in python is this
在python中做这个的另一种方法是。
from operator import itemgetter
sorted(myList, key=itemgetter(1))
#1
6
Assuming that the list of tuples has a type IEnumerable<Tuple<int, int>>
(a sequence of tuples represented using Tuple<..>
class from .NET 4.0), you can write the following using LINQ extension methods:
假设元组列表具有类型IEnumerable
var result = myList.OrderBy(k => k.Item2);
In the code k.Item2
returns the second component of the tuple - in C#, this is a property (because accessing item by index wouldn't be type-safe in general). Otherwise, I think that the code is pretty succinct (also thanks to nice lambda function notation).
在代码中k。Item2返回元组的第二个组件——在c#中,这是一个属性(因为按索引访问项通常不会是类型安全的)。否则,我认为代码非常简洁(也要感谢lambda函数符号)。
Using the LINQ query syntax, you could write it like this (although the first version is IMHO more readable and definitely more succinct):
使用LINQ查询语法,您可以这样编写(尽管第一个版本更易于阅读,而且绝对更简洁):
var result = from k in myList orderby k.Item2 select k;
#2
14
Another way to do it in python is this
在python中做这个的另一种方法是。
from operator import itemgetter
sorted(myList, key=itemgetter(1))