C#List< string>包含来自另一个List< string>的部分匹配 [英] C# List<string> contains partial match from another List<string>
问题描述
我有这些列表:
var list1 = new List<string>
{
"BOM_Add",
"BOM_Edit",
"BOM_Delete",
"Paper_Add",
"Paper_Edit",
"Paper_Delete"
};
var list2 = new List<string> {"BOM", "Paper_Add"};
我想基于部分匹配来创建常见项目的第三个列表.因此,第三个列表应包含:
I want to create a third list of the common items based on a partial match. So, the third list should contain:
"BOM_Add",
"BOM_Edit",
"BOM_Delete",
"Paper_Add"
因为第二个列表包含"BOM".
because the second list contains "BOM".
如果第二个列表包含"_Edit",那么我希望第三个列表具有
If the second list contained "_Edit", then I would expect the third list to have
"BOM_Edit",
"Paper_Edit"
如果我在第二个列表中拼出每一项(例如"BOM_Add"),我都知道如何使用.Intersect()
来做到这一点,但是我需要比这更灵活.
I know how to do this with .Intersect()
if I spell out each item (e.g. "BOM_Add") in the second list, but I need it to be more flexible than that.
是否可以在不迭代第一个列表中的每个项目的情况下完成此操作?这些列表可能会很长,如果可以的话,我宁愿避免这种情况.
Can this be done without iterating through each item on the first list? These lists may get very long and I would prefer to avoid that if I can.
推荐答案
您可以使用LINQ
var result = list1.Where(r => list2.Any(t => r.Contains(t)))
.ToList();
对于输出:
foreach (var item in result)
{
Console.WriteLine(item);
}
输出为:
BOM_Add
BOM_Edit
BOM_Delete
Paper_Add
可以做到这一点而无需遍历第一个项目中的每个项目 列表吗?
Can this be done without iterating through each item on the first list?
您必须通过循环或使用LINQ (内部也进行迭代)进行迭代
You have to iterate, either through a loop or using LINQ (which internally iterates as well)
这篇关于C#List< string>包含来自另一个List< string>的部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!