I have this string:
string alertsId = "1,2,3,4";
Then I convert the string to list of ints:
List<int> list = alertsId.Split(',').Select(n => Convert.ToInt32(n)).ToList();
How can I convert the list above to nullable list of ints?
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
C# 2.0 introduced nullable types that allow you to assign null to value type variables. You can declare nullable types using Nullable where T is a type. Nullable types can only be used with value types. The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value.
A list is never null. The variable might be null, but a list itself is not null. Null is just null, and also has a specific intrinsic meaning.
Well a List<int>
is a reference type and therefor nullable by definition. So I guess you want to create a list of nullable integers (List<int?>
).
You can simply use Cast<T>()
:
List<int?> nullableList = list.Cast<int?>().ToList();
Or to create it directly:
List<int?> list = alertsId.Split(',').Select(n => (int?)Convert.ToInt32(n)).ToList();
Define a function:
public int? ParseToNullable(string s)
{
int? result = null;
int temp = 0;
if (int.TryParse(s, out temp))
{
result = temp;
}
return result;
}
And then use it like this:
string alertsId = "1,2,3,4";
List<int?> list = alertsId.Split(',').Select(n => ParseToNullable(n)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With