Implicit convert List<int?> to List<int>

本文关键字:gt int lt List to convert Implicit | 更新日期: 2023-09-27 17:54:20

我正在使用Linq to Entities

创建一个实体"Order",其中包含一个可空列"SplOrderID"。

我查询我的订单列表

List<int> lst = Orders.where(u=> u.SplOrderID != null).Select(u => u.SplOrderID);

我理解这是因为SplOrderID是一个可空的列,因此选择方法返回可空的int。

我只是希望LINQ聪明一点。

我该如何处理这个?

Implicit convert List<int?> to List<int>

在选择属性时,只需获取可空属性的值:

List<int> lst =
  Orders.Where(u => u.SplOrderID != null)
  .Select(u => u.SplOrderID.Value)
  .ToList();

linq

var lst = (from t in Orders
           where t.SplOrderID.HasValue
           select new Order
           {
             SplOrderID = t.SplOrderID
           }).Select(c => c.SplOrderID.Value).ToList();

   var lst = (from t in Orders
               where t.SplOrderID.HasValue
               select t.SplOrderID.Value).ToList();

我发现你的问题试图解决同样的问题,经过几次尝试,我得到了这个解决方案,为select创建的列表上的每个属性cast int

List<int> lst = Orders.where(u=> u.SplOrderID != null).Select(u => (int)u.SplOrderID);

有用的辅助/扩展方法:

对于其他答案中提到的工作,我通常使用一些helper扩展方法:

public static class IEnumerableExtensions
{
    public static IEnumerable<TKey> GetNonNull<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey?> keySelector) 
        where TKey : struct
    {
        return source.Select(keySelector)
            .Where(x => x.HasValue)
            .Select(x => x.Value);
    }
    // the two following are not needed for your example, but are handy shortcuts to be able to write : 
    // myListOfThings.GetNonNull()
    // whether myListOfThings is List<SomeClass> or List<int?> etc...
    public static IEnumerable<T> GetNonNull<T>(this IEnumerable<T?> source) where T : struct
    {
        return GetNonNull(source, x => x);
    }
    public static IEnumerable<T> GetNonNull<T>(this IEnumerable<T> source) where T : class
    {
        return GetNonNull(source, x => x);
    }
}

你的用法:

// will get all non-null SplOrderId in your Orders list, 
// and you can use similar syntax for any property of any object !
List<int> lst = Orders.GetNonNull(u => u.SplOrderID);

对于在转换

时不想简单忽略空值的读者

值得一提的是GetValueOrDefault(defaultValue)的潜在用途,也许你想保留原始的null值,但将它们转换为一些默认/哨兵值。(以defaultValue参数给出):

例如:

// this will convert all null values to 0 (the default(int) value)
List<int> lst =
     Orders.Select(u => u.GetValueOrDefault())
     .ToList();
// but you can use your own custom default value
const int DefaultValue = -1;
List<int> lst =
     Orders.Select(u => u.GetValueOrDefault(DefaultValue))
     .ToList();