Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make nullable list of int

Tags:

c#

.net

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?

like image 414
Michael Avatar asked Jun 30 '16 10:06

Michael


People also ask

How do you create a nullable integer?

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.

Can int be nullable?

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.

How do you make an int Nullable in C#?

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.

Can a list be nullable?

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.


2 Answers

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();
like image 60
René Vogt Avatar answered Sep 19 '22 01:09

René Vogt


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();
like image 30
Alex Solari Avatar answered Sep 23 '22 01:09

Alex Solari