I have an odd behavior using an IEnumerable<string>
with a ternary operator and a Select
statement.
I have two lists with different objects. One list contains Enums
the other list contains objects. Those objects do have a String
property.
If one list is null
or empty
I want to get the values of the other list.
Here is some code:
public class ExportItem
{
public string Type;
...
}
public enum ExportType
{
ExportType1,
ExportType2,
...
}
The List<ExportItem>
is always filled by a config file. The List<ExportType>
is filled if command line arguments are provided. So if List<ExportType>
is filled I want to use them, otherwise I want to use those from the config file.
So my code ist like this:
IEnumerable<string> exportTypes = MyListOfExportTypes != null &&
MyListOfExportTypes.Any() ? MyListOfExportTypes.Select(x => x.ToString()) :
MyListOfExportItems.Select(x => x.Type);
The thing is that exportTypes
is null
but I don't get it...
When I do this with if-else
everything works as expected. Also if exportTypes
is of type List<string>
and I call ToList()
after the Select
statement everything works fine.
Using var a = MyListOfExportTypes.Select(x => x.ToString());
and var b = MyListOfExportItems.Select(x => x.Type);
does work as expected.
Must be something with the ternary operator and/or IEnumerable
. But what?
Or what do I miss? Any suggestions?
EDIT:
I now have a screenshot...
Note that the code above foreach
works nevertheless...
Not sure if this was answered, But I think that this is related to the fact that you are using LINQ deferred execution.
When writing LINQ queries, there is a difference between creating the query and executing it.
Writing the select statement, is creating the query, adding ToList() executes it. Think of it like writing SQL query in SQL server console (that's the writing stage), and once you hit F5 (Or the play button) you execute it.
I hope this little code sample will help to clarify it.
public class SomeClass
{
public int X { get; set; }
public int Y { get; set; }
public void Test()
{
//Here I'm creating a List of Some class
var someClassItems = new List<SomeClass> {
new SomeClass { X = 1, Y = 1 },
new SomeClass { X = 2, Y = 2 }
};
//Here I'm creating a Query
//BUT, I'm not executing it, so the query variable, is represented by the IEnumerable object
//and refers to an in memory query
var query = someClassItems.
Select(o => o.X);
//Only once the below code is reached, the query is executed.
//Put a breakpoint in the query, click the mouse cursor inside the select parenthesis and hit F9
//You'll see the breakpoint is hit after this line.
var result = query.
ToList();
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments