zoukankan      html  css  js  c++  java
  • c# 关于字典dictionary 按时间排序

    上文中说到sortedlist 排序是键排序,不符合项目要求问题,接着使用字典dictionary  对value 为时间按照升序排序,问题解决.
    中间涉及到linq的使用.还有其他的写法,但发现下边的写法最直观也容易理解.
    var dicSort = from objDic in dic orderby objDic.Value descending select objDic; 这种写法最简单,也容易理解
    dicsort 目标字典,objdic对象应该是映射的无需定义的对象,dic 是你自己定义的字典,orderby 规则,对字典里的每个对象或者叫存值吧,存值的value进行 升序排序,选择这个对象,后边 select 指定选择这个linq要求的格式,没详细了解.
    再看看下边的写法
    对一个Dictionary<TKey, TValue>进行值排序可以用LINQ:  
      
    Dictionary<string, string> MyDictionary = new Dictionary<string, string>();  
      
    MyDictionary = (from entry in MyDictionary   
                                         orderby entry.Value ascending  
                                         select entry).ToDictionary(pair => pair.Key, pair => pair.Value);  

    后边还有个todictionnary, 这个应该是源数据不是字典的形式,转换成字典,而当前我的项目里边使用的是字典处理的,所以不需要转换了.

    定义字典
    static Dictionary<String, DateTime> n_readlist = new Dictionary<String, DateTime>();

     时间变量

    DateTime time = DateTime.Parse(strs[1]);
    添加

      n_readlist.Add(result, time);

    排序升序ascending 

     var dicSort =  from objDic in n_readlist orderby objDic.Value ascending select objDic;  //在此objdic就是n_readlist ,objdic.value 的排序就是n_readlist的排序

    打印

    foreach (var item in dicSort)
    {
    Debug.WriteLine(item.Key+" " + item.Value);
    }


     var dicSort =  from objDic in n_readlist orderby objDic.Value ascending select objDic;
    引用

    这里是针对.NET版本过低的排序方式,没怎么用过,记录一下;

    一、创建字典Dictionary 对象

      假如 Dictionary 中保存的是一个网站页面流量,key 是网页名称,值value对应的是网页被访问的次数,由于网页的访问次要不断的统计,所以不能用 int 作为 key,只能用网页名称,创建 Dictionary 对象及添加数据代码如下:

    复制代码
    Dictionary<string, int> dic = new Dictionary<string, int>();
      dic.Add("index.html", 50);
      dic.Add("product.html", 13);
      dic.Add("aboutus.html", 4);
      dic.Add("online.aspx", 22);
      dic.Add("news.aspx", 18);
    复制代码

    二、.net 2.0 版本 Dictionary排序

    复制代码
    List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(dic);

      //倒叙排列:只需要把变量s2 和 s1 互换就行了 例: return s1.Value.CompareTo(s2.Value);
      //进行排序 目前是顺序

          lst.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)  
          {
            return s2.Value.CompareTo(s1.Value);
          });
          dic.Clear();
    复制代码

     三、.net 3.5 以上版本 Dictionary排序(即 linq dictionary 排序)

      使用linq排序

    var dicSort = from objDic in dic orderby objDic.Value descending select objDic;
    输出要用这个输出:
    foreach(KeyValuePair<string, int> kvp in dicSort)
    {
      Response.Write(kvp.Key + ":" + kvp.Value + "<br />");
    }
  • 相关阅读:
    hadoop与spark的处理技巧(六)聚类算法(3)LDA
    hadoop与spark的处理技巧(一)Top N处理技巧
    从零开始学Python 三(网络爬虫)
    Could not get JDBC Connection--java
    idea函数被调用
    人工智能-我们应该了解什么(一)
    从零开始学Python 二
    从零开始学Python 一
    java8 简便的map和list操作
    Could not autowire. No beans of 'xxxx' type found的错误
  • 原文地址:https://www.cnblogs.com/zuochanzi/p/6819339.html
Copyright © 2011-2022 走看看