Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort in list object

Tags:

c#

linq

I get from database Sytem.Collections.generic.IList and filter it by searchText:

String searchText="E";
var query = something().List();
query = query.Where(x => !string.IsNullOrEmpty(x.Name) &&
x.Name.ContainsInsensitive(searchText)).ToList();
result = query.Select().ToList();

Now I would like that result is sorted by Name column. First all values which starts with searchText and then all values which contains searchText.

If I write this:

result = result.OrderBy(x => x.Name).ToList();

I get result sorted by Name, for example:

1. "A name"    
2. "B name"
3. "E name"
4. "F name"

All this contains e in Name. I would like that my sort is:

1. "E name"    
2. "A name"
3. "B name"
4. "F name"

What should I change in my OrderBy expression?

like image 377
Simon Avatar asked Dec 08 '15 09:12

Simon


People also ask

How do you sort objects in a list?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.

Can you sort a list of objects in Python?

A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.

Can you sort objects in Java?

In Java, we can implement whatever sorting algorithm we want with any type. Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers. The Comparator interface allows us to do the same but in a more flexible way.


3 Answers

Chain together 2 orders with OrderBy and ThenBy

.OrderBy(x => x.Name.StartsWith(searchText) ? 0 : 1)
.ThenBy(x => x.Name)
like image 175
Jamiec Avatar answered Oct 07 '22 01:10

Jamiec


You can do two sorting calls after another (first OrderBy, all subsequent ThenBy):

result.OrderBy(x => !x.Name.StartsWith(searchText)).ThenBy(x => x.Name).ToList();

This will sort true (1) first, then (0) false. The !x.Name makes the order right. Then it sorts on x.Name in both groups.

like image 10
Patrick Hofman Avatar answered Oct 07 '22 00:10

Patrick Hofman


Well, according your code you have result materialized as List<T>:

 result = query.Select().ToList();

And then you're recreating and reassigning the list:

 result = result.OrderBy(x => x.Name).ToList();

So I suggest sorting in-place instead of OrderBy:

  result.Sort((x, y) => {
    if (x.Name.StartsWith(searchText)) {
      if (!y.Name.StartsWith(searchText))
        return 1;
    } 
    else if (y.Name.StartsWith(searchText))
      return -1;

    return String.Compare(x.Name, y.Name);
  });
like image 3
Dmitry Bychenko Avatar answered Oct 07 '22 01:10

Dmitry Bychenko