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

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

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

Here's 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;
}

      

the section ctx.spStoreSearch(storeNumber).Where

saysMethod, Delegate or event is expected

I based what I was currently doing on this answer

Could my error be in the stored procedure itself? This is what I am returning from the storedProcselect * from @TempTable

+3


source to share


3 answers


Select Nullable int value as:

.Select(x => x.Value)

      

You can also do casting, for example:

.Select(x => (int) x)

      



Your request could be:

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

      

You get an exception because your element in List

is of type int?

or Nullable<int>

, so when you do Select(x=> x)

, it selects elements of type int?

and you cannot assign that List<int>

.

+14


source


You have two options, you can either convert the zero integers you have to 0 (or whatever number you choose to choose) and include them in your list, or you can filter them ...



List<int?> nullableInts = new List<int?>();

// Lets generate some data to play with...
for (int i = 0; i < 100; i++)
{
    int? digit = i % 2 == 0 ? (int?)null : i;
    nullableInts.Add(digit);
}

// Below we use the GetValueOrDefault method to convert all null integers to -1
List<int> ints = nullableInts.Select(x => x.GetValueOrDefault(-1)).ToList();

// Below we simply cast the nullable integer to an integer
List<int> filteredInts = nullableInts.Where(x => x.HasValue)
                                     .Select(x => (int)x).ToList();

      

0


source


Selects all nonzero values ​​and adds them to a list of integers (filtered out using the 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();

      

0


source







All Articles