Search List FirstOrDefault StartsWith fuzzy

If I use the following code I will find an Item.ShowName starting with “X” – if one exists.

List<Artist> myList = new List<Artist>();
//Fill list with items
Artist Item = myList.FirstOrDefault(x => x.StartsWith("X"));

My problem is if there is no Item.ShowName starting with “X”. In that case I want the nearest match, i.e. the first Item starting with “Y” or the last Item with “W” in my list. Obviously I can enumerate through the whole list but this might be slow. What is a fast way to get the result?


Here is a little trick you can use to do so :

Artist Item = myList.Where(s => !String.IsNullOrEmpty(s))
                    .OrderBy(x => Math.Abs(x[0] - (int)'X')).FirstOrDefault();

Convert 'X' and first character of x to integer, order by the absolute value of the difference.

Need Your Help

How can I calculate the optimal solution?

java performance algorithm assembly

I have some imaginary hardware. It only has exactly 2 memory addresses and 2 registers. It has only two instructions available - subtract a memory address from a register, and move a register's v...

How to fade color

python image image-processing colors pixel

I would like to fade the color of a pixel out toward white, but obviously maintain the same color. If I have a pixel (200,120,40), will adding 10 to each value to make (210,130,50) make it the same

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.