Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<int?> to List<int> [duplicate]

Tags:

c#

int

nullable

Suppose, I have a list of Nullable Integer's & I want to convert this list into List<int> which contains only values.

Can you please help me to solve this.

like image 514
Amol Bavannavar Avatar asked Jan 29 '15 11:01

Amol Bavannavar


3 Answers

Filter out the null values, get the numbers using Value property and put them into a list using ToList:

yourList.Where(x => x != null).Select(x => x.Value).ToList();

You can also use Cast

yourList.Where(x => x != null).Cast<int>().ToList();
like image 57
Selman Genç Avatar answered Oct 09 '22 20:10

Selman Genç


Have you tried:

List<int> newList = originalList.Where(v => v != null)
                                .Select(v => v.Value)
                                .ToList();

?

like image 45
JLRishe Avatar answered Oct 09 '22 19:10

JLRishe


Try:

 var numbers1 = new List<int?>() { 1, 2, null};
 var numbers2 = numbers1.Where(n => n.HasValue).Select(n => n.Value).ToList();
like image 2
L-Four Avatar answered Oct 09 '22 20:10

L-Four