zoukankan      html  css  js  c++  java
  • linq排序之 根据文本 A-001-002-003 这种类型进行分割排序 空值放于最后

    调用

    1   List<string> data = new List<string>() {
    2                 "D-001-001-001","A-001-004-001","A-001-002-001",
    3                 "A-002-001-001", "F-004-001-001", "A-003-001-001",
    4                 "A-004-001-004","A-041-0401-031","" };
    5             var gf = (from e in data select e).OrderBy(x => x, new AlphaNumericComparer()).ToList();

    比较器

     1   public class AlphaNumericComparer : IComparer<string>
     2     {
     3         public int Compare(string first, string second)
     4         {
     5              int firstNumber, secondNumber;//定义数值类型返回值
     6             if (string.IsNullOrEmpty(first)&& string.IsNullOrEmpty(second))
     7             {
     8                 return 0;
     9             }
    10             if (string.IsNullOrEmpty(first) && !string.IsNullOrEmpty(second))
    11             {
    12                 return 1;
    13             }
    14             if (!string.IsNullOrEmpty(first) && string.IsNullOrEmpty(second))
    15             {
    16                 return -1;
    17             }
    18             //分割字符串
    19             string[] firstArray = first.Split('-');
    20             string[] secondArray = second.Split('-');
    21             List<int> intArray = new List<int>();
    22             //记录比较结果
    23             for (int i = 0; i < firstArray.Length; i++)
    24             {
    25                 bool firstIsNumber = int.TryParse(firstArray[i], out firstNumber);
    26                 bool secondIsNumber = int.TryParse(secondArray[i], out secondNumber);
    27                 if (firstIsNumber && secondIsNumber)
    28                 {
    29                     //数字比较
    30                     intArray.Add(firstNumber.CompareTo(secondNumber));
    31                 }
    32                 else {
    33                     //文本比较
    34                     intArray.Add(firstArray[i].CompareTo(secondArray[i]));
    35                 }
    36             }
    37             intArray.Reverse();//从末位开始计算差值
    38             int val = 0;
    39             //获取差值占比
    40             for (int i = 0; i < intArray.Count; i++)
    41             {
    42                 val += intArray[i] * (i+1) * 10;
    43             }
    44             return val;
    45         }
    46     }

    效果图:

  • 相关阅读:
    MongoDB-基础-limit-skip-sort
    MongoDB-基础-条件操作符
    mongodb-基础-update-remove
    Linq to sql-存储过程
    SQL Server-游标使用
    JavaScript-求时间差
    HTTP 错误 500.21
    .NET错误The 'targetFramework' attribute in the <compilation> element of the Web.config file is used only to target version 4.0 and later of the .NET Framework
    HTTP 错误 500.21
    WebApi&MVC对比
  • 原文地址:https://www.cnblogs.com/nontracey/p/6681372.html
Copyright © 2011-2022 走看看