Ignore "The" and "A" when sorting a list in C #

I am currently making a mini music player / organizer for myself. However, when using the list view, it is sorted alphabetically and does not ignore "The" and "A":

  • I like a lot
  • Adiago for strings
  • Stay crispy
  • Foreseen
  • Pretense time

it should be:

  • Adiago for strings
  • Foreseen
  • I like a lot
  • Stay crispy
  • Time to create

Everything is loaded from a multidimensional array, and I even tried to filter out "The" and "A" manually and then display the real name (from another array), but then it just sorts the display name (including "The" and "A")

+3
source share
3 answers

, comparer ListView, ListView.ListViewItemSorter. "the "" a" .

ListView , , , "a "" a", ListView (.. , ListView - , ).

+5

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);
}

"a" "the" , .

+1

, :

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);
    }
}

The regular expression removes any leading "A" or "The" from the lines so that they do not affect the comparison.

0
source

Source: https://habr.com/ru/post/1719670/


All Articles