Is it better to call ToList() or ToArray() in LINQ queries?
I often run into the case where I want to eval a query right where I declare it. This is usually because I need to iterate over it multiple times and it is expensive to compute. For example:
string raw = "...";
var lines = (from l in raw.Split('
')
let ll = l.Trim()
where !string.IsNullOrEmpty(ll)
select ll).ToList();
This works fine. But if I am not going to modify the result, then I might as well call ToArray()
instead of ToList()
.
I wonder however whether ToArray()
is implemented by first calling ToList()
and is therefore less memory efficient than just calling ToList()
.
Am I crazy? Should I just call ToArray()
- safe and secure in the knowledge that the memory won't be allocated twice?