zoukankan      html  css  js  c++  java
  • c# 集合中有数字、字符的Orderby排序

    string[] things= new string[] { "105", "101", "102", "103", "90","a","B" ,"A","b"};
    foreach (var thing in things.OrderBy(x => x))
    {
        Console.WriteLine(thing);
    }
    输出: 101,102,103,105,90,a,A,b,B
    目标输出: 90,101,102,103,105,a,A,b,B
        foreach (var thing in things.OrderBy(x => x, new SemiNumericComparer()))
        {    
            Console.WriteLine(thing);
        }

     

    public class SemiNumericComparer: IComparer<string>
    {
        public int Compare(string s1, string s2)
        {
            if (IsNumeric(s1) && IsNumeric(s2))
            {
                if (Convert.ToInt32(s1) > Convert.ToInt32(s2)) return 1;
                if (Convert.ToInt32(s1) < Convert.ToInt32(s2)) return -1;
                if (Convert.ToInt32(s1) == Convert.ToInt32(s2)) return 0;
            }
            if (IsNumeric(s1) && !IsNumeric(s2))
                return -1;
            if (!IsNumeric(s1) && IsNumeric(s2))
                return 1;
            return string.Compare(s1, s2, false);
        }
        public static bool IsNumeric(object value)
        {
            try {
                int i = Convert.ToInt32(value.ToString());
                return true; 
            }
            catch (FormatException) {
                return false;
            }
        }
    }
  • 相关阅读:
    [opencv] 生成标定棋盘格
    [opencv] cmake编译opencv并去窗口边框
    [opencv] matlab生成opencv可读的xml
    [matlab] vc++和matlab混合编程
    全息摄影
    [opencv&opengl]多窗口显示
    CPLEX
    ios读取设备姿态并传输
    python: 基本知识记录
    css: position的使用;
  • 原文地址:https://www.cnblogs.com/94cool/p/9314685.html
Copyright © 2011-2022 走看看