Linq OrderBy, but ignore the first word if "

I have the following linq expression for my order, but I was wondering how to change this so that it is ordered by name, but ignores the first word if it is "

CaseStudies.OrderBy(a => a.Name)
+4
source share
3 answers

The simplest way (if there is always a lowercase theand no more than one space between words):

CaseStudies.OrderBy(a => a.Name.StartsWith("the ") ? a.Name.Substring(4) : a.Name)

You can create a method with a beautiful descriptive name and move this logic, as well as check for null and ignore case comparisons:

private string RemoveDefiniteArticle(string s)
{
    if (String.IsNullOrEmpty(s))
        return s;

    if (s.StartsWith("the ", StringComparison.CurrentCultureIgnoreCase))
        return s.Substring(4).TrimStart();

    return s;
}

And use it

CaseStudies.OrderBy(a => RemoveDefiniteArticle(a.Name))
+7
source

There is an amazing amount of edge cases. Suppose your list

List<string> strings = new List<string> { "The aardvark", "the bear", "The  cat", " dog", "  elephant"};

"the"

strings.OrderBy(w => w.StartsWith("the ") ? w.Substring(4) : w);

:

  elephant 
 dog 
the bear 
The  cat 
The aardvark 

strings.OrderBy(w => w.StartsWith("the ", StringComparison.CurrentCultureIgnoreCase) ? w.Substring(4) : w);

:

  elephant 
The  cat 
 dog 
The aardvark 
the bear 

, "the" , :

strings.OrderBy(w => w.StartsWith("the ", StringComparison.CurrentCultureIgnoreCase) ? w.Substring(4).TrimStart() : w);

  elephant 
 dog 
The aardvark 
the bear 
The  cat 

, "the"

strings.OrderBy(w => w.TrimStart().StartsWith("the ", StringComparison.CurrentCultureIgnoreCase) ? w.TrimStart().Substring(4).TrimStart() : w.TrimStart());

:

The aardvark 
the bear 
The  cat 
 dog 
  elephant 

null/empty/whitespace ...

+2
CaseStudies.OrderBy(a => a.Name.TrimStart().StartsWith("the ", StringComparison.CurrentCultureIgnoreCase) ? a.Name.TrimStart().Substring(4).TrimStart() : a.Name)
+1
source

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


All Articles