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 - (int)'X')).FirstOrDefault();
Convert 'X' and first character of x to integer, order by the absolute value of the difference.