The right answer is: it depends.
Jbueno has already explained how works in case your list was created based on data available only in the memory space of the application , ie: that your application mounted alone.
However! LINQ can also be used to get data from a database if you want to completely abstract yourself from the SQL language.
If your list was loaded in real time from a database, Entity Framework , the situation would be quite different.
In this case:
var chaves = new list<string>();
foreach(var item in lista)
{
if(!string.IsNullOrEmpty(item.Chave))
{
chaves.Add(item.Chave);
}
}
You may have made the equivalent of a SELECT
without WHERE
, which can load millions of records into memory. Hence you select the records that interest you in C #. It could be a waste of resources.
In this case:
listaValida = lista.Where(x => !string.IsNullOrEmpty(x.Chave));
foreach(var item in listaValida)
{
chaves.Add(item.Chave);
}
LINQ generates a SQL statement something like this:
SELECT * FROM tabela WHERE chave is not null AND LEN(chave) > 0
This way you can potentially avoid the load and transit of millions of record. This would undoubtedly be faster for most cases.
In both cases, if you use the .ToList()
method your code gets cleaner.