Jon Harding Jon Harding - 1 month ago 15
C# Question

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

Answer

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>.