Home > database >  How can I get the longest string that contains the most occurrences of a character in a list
How can I get the longest string that contains the most occurrences of a character in a list

Time:10-19

This is my list:

List<string> list = new List<string>
{
   "Door Hardware > Door Trim",
   "Door Hardware > Door Trim > Pulls",
   "Door Hardware > Door Trim > Pulls > Flush",
   "Barn Doors & Hardware",
   "Barn Doors & Hardware > Barn Door Hardware",
   "Door Hardware",
   "Brands > Beyerle"
};

The value that I would need from the list is "Door Hardware > Door Trim > Pulls > Flush" which is the longest string that contains the greatest number of '>'.

This is what I have so far using LINQ:

var myVal = list.Where(s => s.Contains('>')).OrderByDescending(s => s.Length).First();

Which would return "Barn Doors & Hardware > Barn Door Hardware" which is not what I need. I would really appreciate your help.

CodePudding user response:

The key here is that you need two levels of ordering.

  1. Order by the number of target characters, descending.
  2. (then) Order by the length of the string, descending.
char target = '>';
string selected = list
    .OrderByDescending(entry => entry.Count(letter => letter == target))
    .ThenByDescending(entry => entry.Length)
    .First();

Important here that you use ThenBy..., which "appends" to the existing ordering rather than overwriting the existing ordering.

Now, you'll still have the problem where multiple inputs could have the same number of target characters and string length. Right now (with both this code and your code), it will choose the first based on the order from the original list. You may want to change that in the future.

CodePudding user response:

You can achieve this by using List.Sort. This would look like that:

list.Sort((x, y) => { return x.Count(s => s == '>') == y.Count(s => s == '>') ? x.Length.CompareTo(y.Length) : x.Count(s => s == '>').CompareTo(y.Count(s => s == '>')); });

All I'm doing here is: Checking if the count of ">" occurrences is equal

if yes, sort by length

if no sort by the count of ">" occurrences.

From that list, the last element would be your result.

  • Related