Orchidee
Orchidee

Reputation: 31

find the longest match of a string in list c#

I have a list of string I need to find the longest match of my search string in the list.

for example the list contains : "test", "abc", "testing", "testingap" and my search string is 'testingapplication'

the result should be 'testingap'

here is what I did so far , it does the work but I'm looking is there any better efficient way to do this

string search= "testingapplication";
List<string> names = new List<string>(new[] { "test", "abc", "testing", "testingap" });
List<string> matchedItems = new List<string>();

foreach (string item in names)
{
        if (search.Contains(item))
        {
            matchedItems.Add(item);
            Console.WriteLine(item);
        } 
}

var WordMatch= matchedItems.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur);
Console.WriteLine("WordMatch"+WordMatch);

Upvotes: 2

Views: 1475

Answers (1)

Rion Williams
Rion Williams

Reputation: 76547

Since you are already using LINQ, you could consider ordering your "names" by length via the OrderByDescending() method and grab the first that contains your string using FirstOrDefault() as seen below:

var match = names.OrderByDescending(n => n.Length)
                 .FirstOrDefault(n => search.Contains(n));

if (match == null)
{
    // No match was found, handle accordingly.
}
else
{
    // match will contain your longest string
}

Upvotes: 10

Related Questions