栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

当字符串为数字时,如何在按值排序时按字母顺序对字符串进行排序?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

当字符串为数字时,如何在按值排序时按字母顺序对字符串进行排序?

将自定义比较器传递到OrderBy。Enumerable.OrderBy将让您指定所需的任何比较器。

这是一种方法:

void Main(){    string[] things = new string[] { "paul", "bob", "lauren", "007", "90", "101"};    foreach (var thing in things.OrderBy(x => x, new SemiNumericComparer()))    { Console.WriteLine(thing);    }}public class SemiNumericComparer: IComparer<string>{    /// <summary>    /// Method to determine if a string is a number    /// </summary>    /// <param name="value">String to test</param>    /// <returns>True if numeric</returns>    public static bool IsNumeric(string value)    {        return int.TryParse(value, out _);    }    /// <inheritdoc />    public int Compare(string s1, string s2)    {        const int S1GreaterThanS2 = 1;        const int S2GreaterThanS1 = -1;        var IsNumeric1 = IsNumeric(s1);        var IsNumeric2 = IsNumeric(s2);        if (IsNumeric1 && IsNumeric2)        { var i1 = Convert.ToInt32(s1); var i2 = Convert.ToInt32(s2); if (i1 > i2) {     return S1GreaterThanS2; } if (i1 < i2) {     return S2GreaterThanS1; } return 0;        }        if (IsNumeric1)        { return S2GreaterThanS1;        }        if (IsNumeric2)        { return S1GreaterThanS2;        }        return string.Compare(s1, s2, true, CultureInfo.InvariantCulture);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576300.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号