Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 750
Wilson Avatar asked Apr 09 '26 00:04

Wilson


2 Answers

if (lists.Any(sublist => sublist.Contains(str)))
like image 181
SLaks Avatar answered Apr 11 '26 14:04

SLaks


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();

enter image description here

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"))...
like image 27
Royi Namir Avatar answered Apr 11 '26 12:04

Royi Namir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!