Michael
Michael

Reputation: 13616

How to make nullable list of int

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?

Upvotes: 13

Views: 47374

Answers (4)

pijemcolu
pijemcolu

Reputation: 2605

My Adition to the linq party

string alertsId = "1,2,3,4,crap";
List<int?> list = alertsId.Split(',')
           .Select(s => { int i; return int.TryParse(s, out i) ? i : (int?)null; })
           .ToList();

First we split by comma, then we try to parse each element, if its not parseable we return null, and then we convert the array we've been working with to a list.

Upvotes: 0

meJustAndrew
meJustAndrew

Reputation: 6613

You can make a list of Nullable and copy each element of your list into the nullable one, like in the example bellow:

            List<Nullable<int>> a = new List<Nullable<int>>();
            List<int> b = new List<int> { 1, 3, 4 };
            foreach (var c in b)
            {
                a.Add((Nullable<int>)c);
            }

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

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();

Upvotes: 21

Alex Solari
Alex Solari

Reputation: 127

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();

Upvotes: 2

Related Questions