简体   繁体   中英

Check if List<List<string>> contains a string

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?

if (lists.Any(sublist => sublist.Contains(str)))
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

ps

ofcourse - this can be shorten to :

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

你可以这样做:

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

只是为了添加现有答案,鉴于您的列表已排序且大, BinarySearch可能比ContainsAny产生更快。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM