获取包含另一个列表的项目列表
请考虑这个字符串列表:获取包含另一个列表的项目列表
Afghanistan, Albania, Algeria, El Salvador, Equatorial, Guinea, Eritrea, Estonia
Ethiopia, Panama, Papua, Paraguay
Peru, Togo, Trinidad & Tobago, Tunisia, Turkey
,我有另一个列表:
tan, ia, Tu
我想包含tan
或ia
或Tu
所有国家。如何在没有foreach
循环的情况下做到这一点?
感谢
回答:
尝试类似的东西;
var listA = new List<string> {"Afghanistan", "England"}; var listB = new List<string> {"afg"};
listA = listA.Where(x => listB.Any(k => x.IndexOf(k, StringComparison.OrdinalIgnoreCase) > -1)).ToList();
此外,我忽略了大小写敏感。如果您想执行区分大小写使用 x.IndexOf(k, StringComparison.Ordinal)
而不是x.IndexOf(k, StringComparison.OrdinalIgnoreCase)
。
回答:
尝试的LINQ这会为您进行循环:
List<string> source = new List<string>() { "Afghanistan", "Albania", "Algeria",
};
string[] filters = new[] {"tan", "ia", "Tu"};
List<string> result = source
.Where(country => filters.Any(filter => country.Contains(filter)))
.ToList();
回答:
尝试一个简单的Where语句与检查所有过滤器里面像这样:
var countries = new List<string> {
"Afghanistan",
"Albania",
"Algeria",
"El Salvador",
"Equatorial",
"Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Panama",
"Papua",
"Paraguay",
"Peru",
"Togo",
"Trinidad & Tobago",
"Tunisia",
"Turkey"
};
var filters = new List<string> {"tan", "ia", "Tu"};
var result = countries.Where(country => filters.Any(filter => country.Contains(filter)));
foreach (var resultItem in result)
{
Console.WriteLine(resultItem);
}
Console.ReadKey();
还要检查它在此琴:https://dotnetfiddle.net/PdZvp4
以上是 获取包含另一个列表的项目列表 的全部内容, 来源链接: utcz.com/qa/261445.html