2017-05-26 68 views
0

我有一個字符串列表,我需要找到列表中搜索字符串的最長匹配。找到列表c中字符串的最長匹配c#

例如列表包含: 「測試」, 「ABC」, 「測試」, 「testingap」 我的搜索字符串是 'testingapplication'

的結果應該是 'testingap'

這裏我做了什麼,到目前爲止,它的工作,但我正在尋找有沒有更好的有效的方法既然你已經在使用LINQ的長度通過做這個

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); 
+0

**如何**它是'不工作'? – hatchet

+0

它正在工作,我正在尋找更好的方式來獲得相同的結果 – Orchidee

回答

7

,你可以考慮訂購您的「姓名」 OrderByDescending()方法並搶先包含你的str使用如下所示的FirstOrDefault()

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 
} 
+0

這實際上是有用的,謝謝 – Orchidee

+0

因爲linq實際上是非常慢我嘗試使用正則表達式,但它只返回第一個匹配,甚至regex.Matches,假設要返回它沒有收集的匹配,這裏是我到目前爲止做的 – Orchidee

+0

var regex = new Regex(string.Join(「|」,names),RegexOptions.Compiled);對於(var match = regex.Match(search); match.Success; match = match.NextMatch()) Console.WriteLine(match.Value); MatchCollection matches = regex.Matches(phoneNumber); foreach(Match匹配匹配) { GroupCollection groupCollection = matche.Groups; Console.WriteLine(matche); } – Orchidee