排序并打印2个元素的列表,而不将排序后的版本保存在另一个列表中

我有一个由2个元素组成的列表,一个字符串和一个浮点数,我试图按照float元素的降序对其进行排序,然后打印列表的前5个元素,但我不想在保存时执行此操作排序列表在另一个列表中。我在最后一行代码上遇到了一些麻烦。这是我的代码,有帮助吗?

var list = new List<Tuple<string, float>>();
for(i=100;i==0;i--){
list.Add(new Tuple<string, float>("randomtext", i);
}

(from s in list orderby s.Item2 descending select s).Take(5);
评论
  • 一起来看雷阵雨
    一起来看雷阵雨 回复

    You are using Tuple<T1, T2> and it has properties like Item1 and Item2 and thus you can do like

    (from s in list         // Here each s is Tuple<string, float>
      orderby s.Item2 descending 
      select s).Take(5);
    

    Well, per your post if you don't want this list to be stored and want to print the selected result then you can use Foreach() method

    list.OrderByDescending(x => x.Item2).Take(5).ToList()
    .Foreach(data =>
    {
     Console.WriteLine(data.Item1 + "\t" + data.Item2);
    });