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?
我如何检查列表
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可能会比包含或任何东西的速度更快。