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?
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.
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.
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.
Chain together 2 orders with OrderBy and ThenBy
.OrderBy(x => x.Name.StartsWith(searchText) ? 0 : 1)
.ThenBy(x => x.Name)
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With