转换泛型.List<;int>;到Generic.List<;int>;

本文关键字:gt int lt List Generic 泛型 转换 | 更新日期: 2023-09-27 18:24:02

我将从存储过程返回一个结果集。它是一个发送回整数列表的临时表。

当我试图返回结果时,我得到一个错误Generic.List<int?> to Generic.List<int>

这就是我正在尝试的:

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

ctx.spStoreSearch(storeNumber).Where部分,它显示Method, Delegate or event is expected

我基于我目前所做的这个答案

我的错误可能在存储过程本身吗?这是我从storedProc select * from @TempTable 返回的内容

转换泛型.List<;int>;到Generic.List<;int>;

选择Nullable int的值,如:

.Select(x => x.Value)

你也可以像一样铸造

.Select(x => (int) x)

您的查询可能是:

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

您得到异常是因为List中的元素类型为int?Nullable<int>,所以当您执行Select(x=> x)时,它选择的是int?类型的项,而不能将其分配给List<int>

选择所有非空值,并将它们添加到整数列表中(使用value属性过滤掉)。

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

您有两个选项,您可以将可为null的整数转换为0(或您决定选择的任何其他数字)并将它们包含在列表中,也可以将它们过滤掉。。。

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