【问题标题】:Sort in alpha order by those that are not prefaced by APPLE and then those that are prefaced with APPLE按字母顺序排序,按字母顺序排序,先按字母顺序,先按字母顺序排列,然后按字母顺序排列。
【发布时间】:2026-01-18 00:05:01
【问题描述】:

我有一个包含以下值的网格

工艺美术

文化

保龄球

科学技术

苹果 - 太棒了

苹果 - 健康

苹果 - 兴趣

苹果 - 营养素

我正在尝试使用比较器,但无法使其正常工作。请帮忙。

Private Function Compare (ByVal x as Object, ByVal y as Object) as Integer Implements Compare

    Dim xCell As String = CType(x, String)
    Dim yCell As String = CType(y, String)
    Dim x1, y1 As Integer

    Dim xReturnVal As String = String.Empty
    Dim xCollection As MatchCollection = Regex.Matches(xCell, "^IAPPLE\s")

    For Each m As Match In xCollection
        xReturnVal += If(m.ToString() = "", "0", "1")
    Next

    If Not xReturnVal = "" Then
        x1 = Convert.ToInt32(xReturnVal)
    End If

    Dim yReturnVal As String = String.Empty
    Dim yCollection As MatchCollection = Regex.Matches(xCell, "^(?!IAPPLE).+")

    For Each mt As Match In yCollection
        yReturnVal += If(mt.ToString() = "", "0", "1")
    Next

    If Not yReturnVal = "" Then
        y1 = Convert.ToInt32(yReturnVal)
    End If

    'Return yReturnVal.CompareTo(xReturnVal)

    Return y1.CompareTo(x1)

End Function 

【问题讨论】:

  • 我认为您在这里不需要正则表达式。如果只有一个字符串以 APPLE 结尾,则返回 1 或 -1。然后,只需比较两个字符串。
  • 你能给我一个更正的sn-p吗?
  • 您可以使用Linq将数据拆分成两个List,分别排序后再加入。
  • 嗨,默认情况下,我按 alpha 顺序排列。当用户点击排序时,这就是我需要对其进行排序的时候。你能给我提供一个使用 IComparer 的工作 sn-p 吗?

标签: c# asp.net wpf vb.net icomparer


【解决方案1】:

用于字符串和对象类型的自定义 IComparer 类。
VB.NetC#。我不知道哪个是首选)。

比较简单:

  • 如果两者都是Objects | Strings 包含 "APPLE",它们照常订购。

  • 如果两个比较元素不包含"APPLE"则相同

  • 如果两个元素之一包含"APPLE",它总是输。

在这里,我使用的是[List<Type>].Sort(new [ComparerClass]());,但它可以与其他方法一起使用。
LINQ 替代:

string[] input = new string[] { "APPLE - Interests", "Arts and Craft", "Science and Technology", "Culture",
                                "APPLE - Nutrients", "APPLE - Awesome", "Bowling", "APPLE - Healthy"};

string[] SortedApples = input.OrderBy(apple => apple, new AppleComparer()).ToArray();

编辑:将Contains() 更改为StartsWith()。这里可能更好。


C# 版本

public class AppleComparer : IComparer<string>, IComparer<object>
{
    public int Compare(string x, string y)
    {
        if (!x.StartsWith("APPLE") & !y.StartsWith("APPLE")) {
            return x.CompareTo(y);
        }
        else if (x.StartsWith("APPLE") & !y.StartsWith("APPLE")) {
            return 1;
        }
        else if (!x.StartsWith("APPLE") & y.StartsWith("APPLE")) {
            return -1;
        }
        else { return x.CompareTo(y); }
    }

    public int Compare(object x, object y)
    {
        return Compare(x.ToString(), y.ToString());
    }
}

可以这样使用:

List<object> ApplesAndCo = new List<object>();
//Or
List<string> ApplesAndCo = new List<string>();
ApplesAndCo.AddRange(new[] { "APPLE - Interests", "Arts and Craft", "Science and Technology", "Culture",
                             "APPLE - Nutrients", "APPLE - Awesome", "Bowling", "APPLE - Healthy"});

ApplesAndCo.Sort(new AppleComparer());

VB.Net 版本。

Public Class AppleComparer
    Implements IComparer(Of String)
    Implements IComparer(Of Object)

    Public Function Compare(x As String, y As String) As Integer Implements IComparer(Of String).Compare
        If (Not x.StartsWith("APPLE")) And (Not y.StartsWith("APPLE")) Then
            Return x.CompareTo(y)
        ElseIf x.StartsWith("APPLE") And Not y.StartsWith("APPLE") Then
            Return 1
        ElseIf Not x.StartsWith("APPLE") And y.StartsWith("APPLE") Then
            Return -1
        Else
            Return x.CompareTo(y)
        End If
    End Function
    Public Function Compare(x As Object, y As Object) As Integer Implements IComparer(Of Object).Compare
        Return Compare(x.ToString(), y.ToString())
    End Function
End Class

VB.Net一些东西:

Dim ApplesAndCo As List(Of Object) = New List(Of Object)()
'Or as a list og String
'Dim ApplesAndCo As List(Of String) = New List(Of String)()

ApplesAndCo.AddRange({"APPLE - Interests", "Arts and Craft", "Science and Technology", "Culture",
                      "APPLE - Nutrients", "APPLE - Awesome", "Bowling", "APPLE - Healthy"})

ApplesAndCo.Sort(New AppleComparer())

【讨论】:

  • 这行得通。谢谢吉米。
  • @Brian 很高兴这很有帮助。检查OrderByDescending() 方法是否按预期工作。
【解决方案2】:

通过请求一个使用Linq对值进行排序的sn-p。

List<string> list = new List<string>();

list.Add("Arts and Craft");
list.Add("APPLE - Nutrients");
list.Add("Science and Technology");
list.Add("Culture");
list.Add("APPLE - Interests");
list.Add("APPLE - Awesome");
list.Add("Bowling");
list.Add("APPLE - Healthy");

var sortedList = list.Where(x => x.Substring(0, 5) != "APPLE").OrderBy(y => y)
                   .Concat(list.Where(x => x.Substring(0, 5) == "APPLE").OrderBy(y => y));

VB

使用https://www.carlosag.net/tools/codetranslator/翻译上述C#代码,所以可能不是100%准确。

Dim list As List(Of String) = New List(Of String)

list.Add("Arts and Craft")
list.Add("APPLE - Nutrients")
list.Add("Science and Technology")
list.Add("Culture")
list.Add("APPLE - Interests")
list.Add("APPLE - Awesome")
list.Add("Bowling")
list.Add("APPLE - Healthy")

Dim sortedList As var = list.Where(() => {  }, (x.Substring(0, 5) <> "APPLE")).OrderBy(() => {  }, y)
                          .Concat(list.Where(() => {  }, (x.Substring(0, 5) = "APPLE")).OrderBy(() => {  }, y))

【讨论】:

  • 您好,感谢您的sn-p。但我怀疑我是否可以在我的 ViewModel 中使用这个列表。我已经通过加载时的 viewModel 以 alpha 顺序(在我的问题中)绑定了列表集合。我想知道如何使用 IComparer 解决此问题。