Home > OS >  C#:How to get the longest common prefix from a list of strings LINQ expression
C#:How to get the longest common prefix from a list of strings LINQ expression

Time:05-09

I am trying to learn LINQ I would like to understand how to get the longest common prefix from a list of strings {"a","abC","abcD"} would return "ab". Common as in at least 1 other string has it. Even though "a" is common for all 3, I would like to get "ab" because 2 elements share this prefix and "ab" is longer than "a"

CodePudding user response:

It was an interesting challenge and this is my solution:

var array = new []{"a","abC","abcD"};

var longestCommonPrefix = Enumerable.Range(1, array.Max(_ => _)!.Length)
            .Select(i =>
            {
                var grouped = array.Where(x => x.Length >= i)
                    .GroupBy(x => x[..i])
                    .Where(x => x.Count() > 1)
                    .OrderByDescending(x => x.Count())
                    .Select(x => new { LongestCommonPrefix = x.Key })
                    .FirstOrDefault();

                return grouped?.LongestCommonPrefix ?? string.Empty;
            }).Max();
  • Related