Reading a xml-file using LINQ-2-XML I have some nullable values (like Int? and DateTime?):
//First Example:
DateTime? date = element.XPathSelectElements("dateFrom")
.Where(i => DateTime.TryParse(i.Value, out DateTime dateFrom))
.Select(i => DateTime.Parse(i.Value))
.FirstOrDefault();
//Second Example
Int? myInt = element.XPathSelectElements("integer")
.Select(e => e.Value.ToString())
.Where(e => Int32.TryParse(e, out int tmpInt))
.Select(e => Int32.Parse(e))
.FirstOrDefault();
In case that date is null and the select-array is empty, linq returns a value instead of null. Refering to my example the myInt
is 0 instead of null (what is a quite big difference when I want to store that in database).
Is it possible to get the null values instead of the "defaults"?
Currently I only use .First() and catch the exception. But in my opinion this is not really clean.
int? myInt = new [] { "", "123", "Foo", "456" }
.Select(s => int.TryParse(s, out int i) ? (int?)i : null)
.FirstOrDefault();
You can use the ternary operator ?
and TryParse
to return a nullable int or null for valid and invalid integer strings respectively.