I want to order elements in a list based on if they are similar (based on string.Contains
) to elements in another list, and then by a default order which is descending string ordinal order.
Given the following data:
var things = new[] {"_1", "_2", "_3", "_4"};
var preferred = new[] { "4", "2" };
Desired result:
1. _4
2. _2
3. _3
4. _1
Linq is preferred but not essential; readability is essential.
My existing solution works, but I don't think is very clear to the reader:
.OrderBy(theString =>
{
for (var i = 0; i < preferred.Length; ++i)
{
if (theString.Contains(preferred[i], StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
return int.MaxValue;
})
.ThenByDescending(x => x.ToLower());