简体   繁体   English

C#:如何从字符串列表LINQ表达式中获取最长公共前缀

[英]C#:How to get the longest common prefix from a list of strings LINQ expression

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".我正在尝试学习 LINQ 我想了解如何从字符串列表 {"a","abC","abcD"} 中获取最长的公共前缀将返回“ab”。 Common as in at least 1 other string has it.常见于至少 1 个其他字符串中。 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"尽管“a”对于所有 3 个都是通用的,但我想得到“ab”,因为 2 个元素共享此前缀并且“ab”比“a”长

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();
var longestCommonPrefix = (words.FirstOrDefault() ?? String.Empty)
    .Substring(0,
      Enumerable.Range(0, words.Any() ? words.Min(x => x.Length) + 1 : 0)
       .Where(x => words.Select(w => w.Substring(0, x))
                     .Distinct().Count() == 1).DefaultIfEmpty(0).Max()
      );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM