检查列表是否包含在另一个列表
问题描述:
我有一个句子一个列表中的元素。我有另一个列表与特定的话。如果句子中至少有一个单词来自下面的列表,我希望列表中的句子。应该选择该句子并将其存储在变量中。检查列表<string>是否包含在另一个列表<string>
List<string> features = new List<string>(new string[] { "battery", "screen", "audio" });
答
的LINQ Any
与Contains
这个应该
List<string> features = new List<string>(){ "battery", "screen", "audio" };
List<string> sentences = new List<string>() { "this is a new screen", "i need a new battery", "there is no foo in my bar" };
List<string> result = sentences.Where(x => features.Any(y => x.Contains(y))).ToList();
+0
该条件将返回“ineedanewbattery” –
+0
的OP如果此应该是有效还是无效不够明确定义 – fubo
答
您可以使用linq。
List<string> features = new List<string>(new string[] { "battery", "screen", "audio" });
// or simpler
//List<string> features = new List<string>{ "battery", "screen", "audio" };
List<string> listOfLines = GetAllLinesHereInList();
var filteredLines = listOfLines.Where(ln=>features.Any(f=>ln.IndexOf(f) > -1));
你尝试过什么吗? –
是的,我已经使用嵌套循环做了..我在寻找一种更好的方式 – kirushan
请包括即使你失败的尝试,所以我们知道你尝试过的东西,没想到我们写代码为您服务。 –