c# - How to search through multiple sets with one linq statement -
consider 3 different lists of strings, 1 of list of lists. need search them find particular one.
in sample, result achieved, in 1 linq statement. note not want change existing collections, nor create new ones.
var collectiona = new list<string>() {"item1", "item2"}; var collectionb = new list<string>() { "item3", "item4" }; var listoflists = new list<list<string>>() {new list<string>() {"item5", "item6"}, new list<string>(){ "item7", "item8"}}; //is there better linq way this? var searchstring = "item5"; var item = collectiona.firstordefault(i => == searchstring); if (item == null) { item = collectionb.firstordefault(i => == searchstring); if (item == null) { foreach (var listoflist in listoflists) { item = listoflist.firstordefault(i => == searchstring); if (item != null) { break; } } } }
bool result = listoflists.selectmany(x => x) .concat(collectiona) .concat(collectionb) .any(x => x == "item5");
Comments
Post a Comment