Maja Okholm
Maja Okholm

Reputation: 3347

What is the best way to search for a string in a list of list of strings c#

What is the best way to search for a string in a list of lists of strings? Example I have many lists of strings e.g. List1 List 2 etc. and all of the lists are collected in a List of Lists (e.g. ListofLists<,...>. Now I want to search for the string "foo" in the list of lists. Is there a way to optimize this in c#?

Thanks in advance

Upvotes: 0

Views: 389

Answers (3)

MetaColon
MetaColon

Reputation: 2871

I'll just summarize/optimize other answers:

The best way to do this is using LINQ. Therefore you could use two ways:

  1. You could flaten the list and look wether it contains an element
  2. You could check all lists wether one list contains the element

Flaten the list

This is done with SelectMany:

listOfLists.SelectMany(x => x).Contains("foo");

SelectMany combines all elements of the sublists and sublists of the sublists (and so on) into one list, so you can check all items, wether one contains the string (https://msdn.microsoft.com/de-de/library/bb534336(v=vs.110).aspx).

Check all lists

This is done with Any:

listOfLists.Any(x => x.Contains("foo"));

Any checks wether any item fulfills the condition (https://msdn.microsoft.com/de-de/library/bb337697(v=vs.110).aspx).

Actually it seems to be more efficient to check all lists (With a randomly generated list with a total of 10,000 entries the first possibility needs averragely 34ms and the second one 31).


In both possibilities I use Contains, which simply checks, wether the list contains the element (https://msdn.microsoft.com/de-de/library/bb352880(v=vs.110).aspx).


Of course you could still use a loop as well:

var contains = false;
foreach (var l in listOfLists)
    foreach (var i in l)
        if (i == "foo")
        {
            contains = true;
            goto end;
        }
end:

But this is less readable, less effective, more complicated and less elegant.

However, if you don't just want to check, wether it exists, but do a bit more with it, the last possibility is possibly the easiest one. If you want an optimized version for another case, feel free to specify your requirements.

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117175

Does this work?

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

// insert code to populate listOfLists

var containsFoo = listOfLists.SelectMany(x => x).Any(x => x == "foo");

Upvotes: 1

degant
degant

Reputation: 4981

Using Linq:

To check if any of the lists contains the string 'foo':

collection.Any(x => x.Contains("foo"));

To get the particular list which contains the string 'foo':

collection.FirstOrDefault(x => x.Contains("foo"));

Upvotes: 1

Related Questions