Reputation:
More specifically in a LINQ to Entities query:
List<string> myResult = (from myTable do some joins...blah).ToList();
if(myResuly.Any())
{
// Foo
}
My question is how do we know if we can use
List<string> myResult = (from myTable do some joins...blah).ToList();
or we should use:
List<string> myResult = new List<string>();
myResult = (from myTable do some joins...blah).ToList();
Upvotes: 0
Views: 109
Reputation: 186708
We should never use (though it's safe) the code like that:
List<string> myResult = new List<string>();
myResult = ... // myResult is reassinged here and "new List<string>()" just lost
since you're just creating useless List<string>
instance. Put instead
List<string> myResult = WhatEver(...).ToList();
Upvotes: 1
Reputation: 17616
If you can already get the list why waste an extra line of code?
List<string> myResult = new List<string>();
The whole idea of initializing your list, is that you don't already have one that you can stock in 'myResult'.
Imagine trying to access your list that you haven't initialized yet.
Upvotes: 1
Reputation: 29073
If there is a function on the right side of the =
that is generating the value, you don't need new
. In your 3rd example, the list you new
is immediately thrown away and the one returned by ToList() is used in it's place
Upvotes: 2