如何在c#中忽略字符串空间从列表中检索字符串元素



简单问题。

我有一个字符串变量,叫做";searchTerm";以及字符串列表。如何在忽略空白的情况下检索与searchTerm变量匹配的某个元素。我一直试图做但没有成功的一个例子:

string searchTerm = "The Lord Of The Rings"
List<string> films = new List<string>(){ "Harry Potter", "Avangers", "The Lord  Of The Rings", "Back to the future"};
string film = films.where(film => film.Contains(searchTerm, StringComparison.OrdinalIgnoreCase));

此代码不起作用。请理解,在电影列表中;《指环王》;字符串在Lord word后面有两个空格,searchTerm只有一个空格。

我尝试过以下几种,但没有成功:

string film = films.where(film => film.Replace(" ","").Contains(searchTerm.Replace(" ",""), StringComparison.OrdinalIgnoreCase));

你能帮我找到解决办法吗?感谢

}

为什么不使用简单的正则表达式替换和字符串比较?DotNet Fiddle

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;                  
string searchterm = "The Lord Of The Rings";
List<string> films = new List<string> { "Harry Potter", "Avangers", "The Lord  Of The Rings", "Back to the future"};
string film = films
.FirstOrDefault(f => string.Equals(Regex.Replace(f, "\s", ""), Regex.Replace(searchterm, "\s", ""), StringComparison.CurrentCultureIgnoreCase));

最新更新