Selecting a subset of a list with a special item first in the list

I have a list in C # providers, everyone has a Name property. I want to allow the user to filter this list by searching for a name. The filter string can be partial or full. However, if the resulting list contains an exact match, it must be at position zero in the list with all partial matches after that.

I can easily get a sub-list using linq and lambdas, but I need to resort to hacking to create a second list if there is an exact match, adding it and then adding the remaining matches without the exact one. He feels inelegant. Is there an easier way? My current code (made from memory, so it cannot 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;
}
+3
4

StringComparer, Levenshtein distance - - . , , ( , ) .

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

, , int.MinValue , CompareTo(). ().

+3

-, tvanfosson .

, :

vendors.Where(v => v.Name.ToUpper().Contains(vendorNameSearch))
       .OrderBy(v => !string.Equals(v.Name, vendorNameSearch))
       .ThenBy(v => v.Name)
       .ToList();

, . - , , false. , OrderByDescending, .

+3

, , ,

List<String> strings = new List<String> {"Cat","Dog","Pear","Apple","Catalog"};

var results = (from st in strings
    where st == "Cat"
    select new {Priority = 1,st}).Union(

    from st in strings
    where st.Contains("Cat")
    select new {Priority = 2, st}).OrderBy(x => x.Priority).Select(x=> x.st).Distinct();
+1

. (abs. Diff. = 0), 0:

var list = vendors.Where(v => v.Name.ToUpper().Contains(vendorNameSearch))
                  .OrderBy(v => Math.Abs(v.Name.ToUpper().Length - vendorNameSearch.Length)));

, .

, , , , .

+1

Source: https://habr.com/ru/post/1714831/


All Articles