Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Generic.List<int?> to Generic.List<int>

I am returning a result set from a stored procedure. It is one temporary table that sends back a list of integers.

When I try to return the results I get an error Generic.List<int?> to Generic.List<int>

This is what I'm trying:

using (SecurityEntities ctx = new SecurityEntities())
{
    List<int> newList = ctx.spStoreSearch(storeNumber).Where(x => x != null).Select(x => x).ToList();
   return test;
}

under the ctx.spStoreSearch(storeNumber).Where section it says Method, Delegate or event is expected

I based what I've currently done on this answer

Could my error be in the stored procedure itself? This is what I'm returning from the storedProc select * from @TempTable

like image 214
Jon Harding Avatar asked Sep 23 '14 17:09

Jon Harding


2 Answers

Select the value of Nullable int like:

.Select(x => x.Value)

You can also do casting like:

.Select(x => (int) x)

Your query could be:

List<int> newList = ctx.spStoreSearch(storeNumber)
                        .Where(x => x.HasValue)
                        .Select(x => x.Value).ToList();

You are getting the exception because your element in the List is of type int? or Nullable<int> so when you do Select(x=> x) it is selecting items of type int? and you can't assign that to List<int>.

like image 80
Habib Avatar answered Oct 05 '22 07:10

Habib


Selects all not null values and add them into a list of integers (filtered out by using value property) .

//select int list
var nullableListIds = nullableListRecords.Select(o => o.ID).ToList();

//create list
var intList =  nullableListIds.Where(n => n != null).Select(n => n.Value).ToList();
like image 39
Wesam Avatar answered Oct 05 '22 08:10

Wesam