When searching for an item in the general list, use LINQ or Contains?

I have a generic Listone and I have to find a specific line in this list. Could you tell me which one works best below?

if (strlist.Contains("Test"))
{
    // String found
}

or

string res = (from d in strlist where d == "Test" select d).SingleOrDefault();

if (res == "Test")
{
    //found
}

Please think that the list can be very large, populated from the database. Your thoughts on this are much appreciated.

+3
source share
3 answers

If you have List<string>(or even IEnumerable<string>) and Contains that meets your needs, use Contains.

If you need additional processing that Contains does not provide, I would suggest using Any ():

if(strList.Any(s => s.StartsWith("Tes"))
{
    // Found
}
+5
source

-, ; true, - .

, SingleOrDefault FirstOrDefault.

, Contains, Any, .

:

if (strings.Contains("SomeString", StringComparer.OrdinalIgnoreCase))

if (strings.Any(s => s.StartsWith("b"))
+2

HashSet<string>, Contains . , , .

var list = BuildListOfStrings();
var set = new HashSet<string>(list);

if (set.Contains("Test"))
{
    // ...
}

O(1).

Test

static void Main(string[] args)
{
    var lst = GenerateStrings().Take(5000000).ToList();
    var hsh = new HashSet<string>(lst);
    var found = false;
    var count = 100;
    var sw = Stopwatch.StartNew();

    for (int i = 0; i < count; i++)
    {
        hsh = new HashSet<string>(lst);
    }
    Console.WriteLine(TimeSpan.FromTicks(sw.ElapsedTicks / count));

    sw = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        found = lst.Contains("12345678");
    }
    Console.WriteLine(TimeSpan.FromTicks(sw.ElapsedTicks / count));

    sw = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        found = hsh.Contains("12345678");
    }
    Console.WriteLine(TimeSpan.FromTicks(sw.ElapsedTicks / count));

    Console.WriteLine(found);
    Console.ReadLine();
}

private static IEnumerable<string> GenerateStrings()
{
    var rnd = new Random();
    while (true)
    {
        yield return rnd.Next().ToString();
    }
}

0.308438 s
0.0197868 s
0.0 s

? Contains, List<string>, HashSet<string>.

0
source

Source: https://habr.com/ru/post/1756980/


All Articles