Skip to main content
 首页 » 编程设计

C# 排序字典列表除了第一对

2024年02月05日14luoye11

我正在尝试对字典进行排序

class Program { 
    static void Main() 
    { 
        // Example dictionary. 
        var dictionary = new Dictionary<string, int>(5); 
        dictionary.Add("cat", 3); 
        dictionary.Add("dog", 1); 
        dictionary.Add("mouse", 0); 
        dictionary.Add("elephant", 2); 
        dictionary.Add("bird", 4); 
 
        var items = from pair in dictionary 
                orderby pair.Value ascending 
                select pair; 
 
        // Display results. 
        foreach (KeyValuePair<string, int> pair in items) 
        { 
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value); 
        } 
        items = from pair in dictionary 
        orderby pair.Value descending 
        select pair; 
    } } 

结果是

mouse 
dog 
elephant 
cat 
bird 

但是我需要排除第一对来对其余的进行排序并得到这个结果

cat 
mouse 
dog 
elephant 
bird    

我可以在这里做任何事情吗?

var items = from pair in dictionary 
                orderby pair.Value ascending 
                select pair; 

请您参考如下方法:

我建议使用 Linq

    var result = dictionary 
        .Take(1)                        // Take first element 
        .Concat(dictionary              // Skip first element and sort the rest on value.  
                .Skip(1) 
                .OrderBy(o=>o.Value)) 
        .Select(x=>x.Key); 

输出

   cat   , 
   mouse   , 
   dog   , 
   elephant   , 
   bird 

检查这个Demo