The right answer is: it depends.
jbueno already explained how it works in case your list was created based on data available only in the application memory space, i.e.: that your application assembled alone.
However! LINQ can also be used to obtain data from a database, if you want to completely abstract yourself from the SQL language.
If your list was uploaded in real time from a database, via Entity Framework, the situation would be quite different.
In that case:
var chaves = new list<string>();
foreach(var item in lista)
{
if(!string.IsNullOrEmpty(item.Chave))
{
chaves.Add(item.Chave);
}
}
You may have done the equivalent of a SELECT
without WHERE
, that can carry millions of records to memory. Hence you select the records that interest you in C#. It can be a waste of resources.
In that case:
listaValida = lista.Where(x => !string.IsNullOrEmpty(x.Chave));
foreach(var item in listaValida)
{
chaves.Add(item.Chave);
}
LINQ generates an SQL command more or less like this:
SELECT * FROM tabela WHERE chave is not null AND LEN(chave) > 0
This way, you can potentially avoid loading and transit millions of registrations. This form would undoubtedly be faster for most cases.
In both cases, if you use the method .ToList()
your code gets cleaner.
The second code is faster and more readable.
– PauloHDSousa