2016-04-14 18 views
0

环顾四周,发现许多类似的问题,但没有一个与我的完全匹配。如果列表中的字符串出现在字符串中,然后添加到列表

public bool checkInvalid() 
    { 
     invalidMessage = filterWords.Any(s => appmessage.Contains(s)); 
     return invalidMessage; 
    } 

如果找到与列表中的字符串匹配的字符串,则布尔值invalidMessage设置为true。 之后,虽然我希望能够将每个找到的字符串添加到列表中。有没有一种方法我可以使用.Contains()来做到这一点,或者可以有人推荐我另一种方式去做这件事? 非常感谢。

回答

0

那么从你的描述,我还以为这里是你想要的东西:

// Set of filtered words 
string[] filterWords = {"AAA", "BBB", "EEE"}; 

// The app message 
string appMessage = "AAA CCC BBB DDD"; 

// The list contains filtered words from the app message 
List<string> result = new List<string>(); 

// Normally, here is what you do 
// 1. With each word in the filtered words set 
foreach (string word in filterWords) 
{ 
    // Check if it exists in the app message 
    if (appMessage.Contains(word)) 
    { 
     // If it does, add to the list 
     result.Add(word); 
    } 
} 

但正如你所说,你想要使用LINQ,所以你可以这样做:

// If you want to use LINQ, here is the way 
result.AddRange(filterWords.Where(word => appMessage.Contains(word))); 
+0

正是我在寻找的感谢! :) –

0

如果你想要的是获取包含在appmessage可以使用WherefilterWords的话:

var words = filterWords.Where(s => appmessage.Contains(s)).ToList(); 
相关问题