Selecting A Subset Of A List With A Particular Element First In The List

c#, linq

Solution

How about developing a StringComparer that computes the Levenshtein distance -- for exact matches this ought to be zero -- and ordering the results by this in ascending order. This way you get your exact match first AND the rest of the results are ordered by the similarity (at least one measure of it) to the search string.

var list = vendors.Where( v => v.Name.ToUpper().Contains( vendorNameSearch ) )
                  .OrderBy( v => ComputeLevenshtein( v.Name.ToUpper(),
                                                     vendorNameSearch ) );

Or you could make a comparer that orders things with exact matches being int.MinValue and all other values being the result of CompareTo(). This would also order the exact match(s) first.

Problem

I have a list in C# of Vendors that all have a Name property. I want to allow a user to filter that list by searching for a Name. The filter string can be a partial or complete match. However, if the resulting list contains an exact match, it should be in position zero in the list with all partial matches after that. I can get the sub-list pretty easily with linq and lambdas but I'm having to resort to a hack of creating a second list if an exact match exists, adding it, and then adding the rest of the matches without the exact one. It feels inelegant. Is there an easier way? My current code (done from memory so it may not compile): ``` List<Vendor> temp = vendors.Where(v => v.Name.ToUpper().Contains(vendorNameSearch)).ToList(); Vendor exactMatch = vendors.Single(v => v.Name.ToUpper().Equals(vendorNameSearch)); if(null == exactMatch){return temp;} else { List<Vendor> temp1 = new List<Vendor>(); temp1.Add(exactMatch); temp1.AddRange(temp.Remove(exactMatch)); return temp1; } ```

Original source