我正在尝试检查两个列表,例如看起来像这样
list1 = {"br","je"};
list2 = {"banana", "bread", "jam", "brisket", "flakes", "jelly"};
应该回来
{false, true, false, true, false, true}
使用LINQ可以实现上述输出。我在下面尝试过这样的东西
public static IEnumerable<bool> ContainsValues(List<string> list1, List<string> list2)
{
List<bool> res = new List<bool>();
foreach (string item in list1)
{
foreach (string sub in list2)
{
res.Add(item.ToLower().Contains(sub.ToLower()));
}
}
return res;
}
最佳答案
是的,您可以在一个语句中重新编写现有代码:
public static IEnumerable<bool> ContainsValues(List<string> list1, List<string> list2)
{
return
from item in list1
from sub in list2
select item.ToLower().Contains(sub.ToLower());
}
但是,您现有的代码无法提供所需的示例结果。为了获得您想要的结果,我想您需要这样的东西:
public static IEnumerable<bool> SecondContainsFirst(List<string> first,
List<string> second)
{
return second.Select(s => first.Any(f =>
s.IndexOf(f, StringComparison.OrdinalIgnoreCase)) > -1);
}
这是示例用法:
private static void Main()
{
var list1 = new List<string> {"br", "je"};
var list2 = new List<string> {"banana", "bread", "jam", "brisket", "flakes", "jelly"};
var result = SecondContainsFirst(list1, list2);
Console.WriteLine($"{{{string.Join(", ", result)}}}");
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
输出量