C#返回与Contains找到的匹配项

时间:2016-04-14 22:20:20

标签: c# linq

我需要返回在比较文本块和字符串列表时找到的所有匹配项。

if(myList.Any(myText.Contains))

我可以验证是否与上述内容匹配,但我不确定如何更进一步并返回匹配的字符串。我查看了Intersect,但据我所知,它仅适用于两种相同的类型。

示例数据:

myList[] = { "City of London", "City of Edinburgh" }; etc
myText = "I am applying for the position in the City of London";

这里所需的结果将是"伦敦金融城",或者通过将结果匹配设置为字符串,或者返回myList的索引。任何帮助非常感谢,谢谢!

3 个答案:

答案 0 :(得分:0)

试试这个:

string result= myList.FindAll(x=> myText.IndexOf(x)>-1);

答案 1 :(得分:0)

这应该有用。

        List<string> myList = new List<string>();
        myList.Add("City of London");
        myList.Add("City of Edinburgh"); 
        string myText = "I am applying for the position in the City of London";

        var result = myList.Where(x => myText.Contains(x)).ToList();

答案 2 :(得分:0)

var matches = myList.Where(a => myText.IndexOf(a) > 0).ToList();