I have a standard List<Uri>
defined that contains a short list of items. I'd like to iterate over the list using a foreach() but would like to 'bring to the top' those items that contain a specific string value in order to process them first. Is this possible with the OrderBy() and, better yet, is it possible in a single line?
Thanks!
In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.
OrderBy" function utilizes the default comparer for a string. That comparer is not necessarily going to return a sort order based on the ASCII code. For a list of all the different string comparers, see the article on MSDN.
OrderByDescending sorts the collection in descending order. OrderByDescending is valid only with the Method syntax. It is not valid in query syntax because the query syntax uses ascending and descending attributes as shown above. Example: OrderByDescending C#
To sort a result set in ascending order, you use ASC keyword, and in descending order, you use the DESC keyword.
You can do that:
foreach(var uri in uriList.OrderByDescending(uri => uri.ToString().Contains("foo"))
{
// Use uri
Yes. you can use OrderByDescending()
using an order that returns a boolean - example:
var results = items.OrderByDescending( x => x.Name=="Herbert").ToList();
In this case the order would return true
for "Herbert" and false
for all other values. All true
values will be ordered after all false
values - we reverse the order by using OrderByDescending()
and have the desired outcome.
Adapted to your Uri
list and Contains()
which also returns a boolean this would mean:
foreach(var uri in uriList.OrderByDescending(x => x.ToString().Contains(someString))
{
//..
}
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