Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<Uri>.OrderBy() sort order based upon Contains()?

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!

like image 946
McArthey Avatar asked Sep 20 '11 20:09

McArthey


People also ask

What is the use of OrderBy in C#?

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.

Does OrderBy work on string?

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.

What is OrderByDescending?

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#

Which method would order a result set in ascending order by the Field ID '? C#?

To sort a result set in ascending order, you use ASC keyword, and in descending order, you use the DESC keyword.


2 Answers

You can do that:

foreach(var uri in uriList.OrderByDescending(uri => uri.ToString().Contains("foo"))
{
    // Use uri
like image 68
Reed Copsey Avatar answered Sep 19 '22 01:09

Reed Copsey


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))
{
   //..
}
like image 27
BrokenGlass Avatar answered Sep 22 '22 01:09

BrokenGlass