C# “忽略”;";及;A「;在C中对listview排序时#
目前我正在为自己制作一个迷你音乐播放器/组织者。但是,当使用列表视图时,它会按字母顺序排序,并且不会忽略“The”和“a”:C# “忽略”;";及;A「;在C中对listview排序时#,c#,.net,sorting,listview,C#,.net,Sorting,Listview,目前我正在为自己制作一个迷你音乐播放器/组织者。但是,当使用列表视图时,它会按字母顺序排序,并且不会忽略“The”和“a”: 很像我 阿迪戈为弦乐 保持松脆 预见 是时候假装了 应该是: 阿迪戈为弦乐 预见 很像我 保持松脆 是时候假装了 它都是从多维数组加载的,我甚至尝试过手动过滤出“The”和“a”,然后显示真实名称(从不同的数组),但它只是对显示的名称进行排序(包括“The”和“a”)您可以使用如下自定义比较方法: using System; using System.Collection
它都是从多维数组加载的,我甚至尝试过手动过滤出“The”和“a”,然后显示真实名称(从不同的数组),但它只是对显示的名称进行排序(包括“The”和“a”)您可以使用如下自定义比较方法:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Example
{
static void Main()
{
List<String> names = new List<String>
{
"A Lot Like Me",
"Adiago For Strings",
"Stay Crunchy",
"The Foresaken",
"Time to Pretend"
};
names.Sort(smartCompare);
}
static Regex smartCompareExpression
= new Regex(@"^(?:A|The)\s*",
RegexOptions.Compiled |
RegexOptions.CultureInvariant |
RegexOptions.IgnoreCase);
static Int32 smartCompare(String x, String y)
{
x = smartCompareExpression.Replace(x, "");
y = smartCompareExpression.Replace(y, "");
return x.CompareTo(y);
}
}
使用系统;
使用System.Collections.Generic;
使用System.Text.RegularExpressions;
课例
{
静态void Main()
{
列表名称=新列表
{
“很像我”,
“阿迪亚戈的弦乐”,
“保持松脆”,
“被预见者”,
“是时候假装了”
};
名称。排序(smartCompare);
}
静态正则表达式SmartCompareeExpression
=新正则表达式(@“^(?:A | The)\s*”,
RegexOptions.Compiled|
RegexOptions.CultureInvariant|
RegexOptions.IgnoreCase);
静态Int32 smartCompare(字符串x、字符串y)
{
x=smartCompareExpression.Replace(x,“”);
y=smartCompareExpression.Replace(y,“”);
返回x.CompareTo(y);
}
}
正则表达式从字符串中去掉任何前导的“A”或“The”,这样它们就不会影响比较。您可以创建一个客户,并使用属性在您的
ListView
实例上设置它。然后,比较器负责从要比较的项目的开始处删除“the”和“a”
当您的
列表视图
排序时,它将使用此自定义比较器进行排序,但原始值(包括“the”和“a”)将用作列表视图
中的显示值(即,您不需要修改您在列表视图
中输入的值-排序时比较器只会忽略您希望它显示的单词).这种LINQ方法似乎有效:
string[] input = new string[] {
"A Lot Like Me",
"Adiago For Strings",
"Stay Crunchy",
"The Foresaken",
"Time to Pretend"
};
IEnumerable<string> ordered = input.OrderBy(s =>
s.StartsWith("A ", StringComparison.OrdinalIgnoreCase) || s.StartsWith("The ", StringComparison.OrdinalIgnoreCase) ?
s.Substring(s.IndexOf(" ") + 1) :
s);
foreach (var item in ordered)
{
Console.WriteLine(item);
}
string[]输入=新字符串[]{
“很像我”,
“阿迪亚戈的弦乐”,
“保持松脆”,
“被预见者”,
“是时候假装了”
};
IEnumerable ordered=input.OrderBy(s=>
s、 StartsWith(“A”,StringComparison.OrdinalIgnoreCase)| s.StartsWith(“The”,StringComparison.OrdinalIgnoreCase)?
s、 子字符串(s.IndexOf(“”+1):
s) );
foreach(订单中的var项目)
{
控制台写入线(项目);
}
它从比较中去掉前导的“a”和“the”,但不改变列表中的值