检查列表>是否包含字符串。

时间:2021-06-21 01:34:58

How can I check if any List<string>s in a List contain a given string? I know how to do this with a loop, but is there a way with LINQ/in one line?

我如何检查列表 s是否包含给定字符串?我知道如何用一个循环来做这个,但是是否有一个方法用LINQ/在一行?

4 个解决方案

#1


9  

if (lists.Any(sublist => sublist.Contains(str)))

#2


1  

var t=lists.SelectMany(f=>f).Contains("str");

full sample :

完整的示例:

var lists = new List<List<string>>();

lists.Add(new List<string>(){"a","b"});
lists.Add(new List<string>(){"b","2"});
lists.Add(new List<string>(){"c","5"});
lists.Add(new List<string>(){"d","7"});

var t=lists.SelectMany(f=>f);

t.Dump();

检查列表>是否包含字符串。

if (t.Contains("k")) 
  Console.WriteLine ("yes") ;
else 
  Console.WriteLine ("no");

result

结果

no

p.s.

注。

ofcourse - this can be shorten to :

当然,这可以缩短为:

if (lists.SelectMany(f=>f).Contains("k"))...

#3


0  

You can do this:

你可以这样做:

bool ifExists = list.Any(x => x.Contains(yourString));

#4


0  

Just to add to existing answers, given your lists are sorted and large, BinarySearch may yield faster than Contains or Any.

仅仅为了增加现有的答案,考虑到你的列表是有序的和大型的,BinarySearch可能会比包含或任何东西的速度更快。

#1


9  

if (lists.Any(sublist => sublist.Contains(str)))

#2


1  

var t=lists.SelectMany(f=>f).Contains("str");

full sample :

完整的示例:

var lists = new List<List<string>>();

lists.Add(new List<string>(){"a","b"});
lists.Add(new List<string>(){"b","2"});
lists.Add(new List<string>(){"c","5"});
lists.Add(new List<string>(){"d","7"});

var t=lists.SelectMany(f=>f);

t.Dump();

检查列表>是否包含字符串。

if (t.Contains("k")) 
  Console.WriteLine ("yes") ;
else 
  Console.WriteLine ("no");

result

结果

no

p.s.

注。

ofcourse - this can be shorten to :

当然,这可以缩短为:

if (lists.SelectMany(f=>f).Contains("k"))...

#3


0  

You can do this:

你可以这样做:

bool ifExists = list.Any(x => x.Contains(yourString));

#4


0  

Just to add to existing answers, given your lists are sorted and large, BinarySearch may yield faster than Contains or Any.

仅仅为了增加现有的答案,考虑到你的列表是有序的和大型的,BinarySearch可能会比包含或任何东西的速度更快。