[英]Sorting a list of objects by a string field by letter then number?
What's a good way to sort an object with a list of strings that are alphanumeric?使用字母数字字符串列表对对象进行排序的好方法是什么?
I have a list of objects like this.我有一个像这样的对象列表。
public class ObjectA
{
public string A {get; set;}
}
var listOfItems = new List<ObjectA>()
{
new ObjectA() { A = "0000003F" },
new ObjectA() { A = "00000035" },
new ObjectA() { A = "TESTTEST" },
new ObjectA() { A = "000633BX" }
};
and when I use LINQ to sort these:当我使用 LINQ 对这些进行排序时:
var sortedList = listOfItems.OrderBy(x => x.A);
I get this list:我得到这个列表:
00000035
0000003F
D0000033
12345678
0A000033
000633BX
TESTTEST
But would like this instead:但是想要这样:
D0000033
TESTTEST
0A000033
0000003F
00000035
000633BX
12345678
How can I make the sorting be done by letter then number?如何使排序先按字母然后按数字完成?
String is of fixed length at 8 characters all alphanumeric no special characters.字符串长度固定,为 8 个字符,全部为字母数字,无特殊字符。
Your algorithm for ordering isn't clear, but here's an approach you can take.您的订购算法尚不清楚,但您可以采用以下方法。 First, define a custom comparer:首先,定义一个自定义比较器:
public class ObjectAComparer : IComparer<ObjectA>
{
public int Compare(ObjectA x, ObjectA y)
{
// Quite possibly not the ordering logic you want. Change as needed.
// "IsNumber" means what you seem to have defined as numbers.
bool xIsNumber = x.A.Any(c => char.IsNumber(c));
bool yIsNumber = y.A.Any(c => char.IsNumber(c));
bool sameKind = !(xIsNumber ^ yIsNumber);
if (sameKind) return x.A.CompareTo(y.A); // Both numbers or both not numbers
if (xIsNumber) return 1;
return -1;
}
}
Then you can use the overload of OrderBy that takes a comparer:然后你可以使用带比较器的 OrderBy的重载:
var sortedList = listOfItems.OrderBy(x => x, new ObjectAComparer());
Output:输出:
TESTTEST
00000035
0000003F
000633BX
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.