Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a List<string> comparing with a string

I need to sort a List<string> by comparing the list with a string

for example: I have a List that contains the following Items.

Kaboki
kriiki
Kale
Kutta
Kiki
Kicki
Krishna
Kseaki

The search keyword is ki I need to sort the list items using the keyword in such a way that, the strings that match in the string start have should be first and the string having the matched string in the other position have to be in the last

Here is my current code

    public static List<string> GetLocations(string prefixText)
    {
        try
        {
            DataTable dtlocs = (DataTable) HttpContext.Current.Session["locations"];
            var dValue = from row in dtlocs.AsEnumerable()
                         where row.Field<string>("Location_Name").ToLower().Contains(prefixText.ToLower())
                         select row.Field<string>("Location_Name");

            var results = dValue.OrderBy(s => s.IndexOf(prefixText, StringComparison.Ordinal));
            var str = new List<string>(results.ToList());

            if (!str.Any())
                str.Add("No locations found");
            return str;
        }
        catch (Exception)
        {
            var str = new List<string> {"No locations found"};
            return str;
        }
    }

Here I'm able to get the first matched values to the top but cannot sort the remaining values

and I have another issue. there is a word King Koti and i'm searhing for Ko and this word comes to first.I think this happens because, the string has two sub strings and one of the substrings start with the matched word.

and can I make the matched letters to bold ??

like image 836
Krishna Thota Avatar asked Dec 04 '25 07:12

Krishna Thota


2 Answers

var res = list.OrderBy(y=> !y.StartsWith("Ki", StringComparison.OrdinalIgnoreCase))
              .ThenBy(x => x)
like image 178
Damith Avatar answered Dec 06 '25 21:12

Damith


OrderBy orders false before true:

var result = list.OrderBy(s => !s.StartsWith("ki", StringComparison.OrdinalIgnoreCase))
                 .ThenBy(s => !s.ToLower().Contains("ki"));
like image 23
cuongle Avatar answered Dec 06 '25 22:12

cuongle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!