将List<int?>隐式转换为List<int>

32

我正在使用Linq to Entities。

有一个实体 "Order",它有一个可空列 "SplOrderID"。

我查询我的订单列表如下:

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

我理解这是因为SplOrderID是可空列,所以Select方法返回可空整数。

我只是希望LINQ能够更加智能一些。

我该如何处理?

4个回答

61

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

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

2

我发现你尝试解决相同的问题,经过几次尝试,我得到了这个解决方案,在由select创建的列表中为每个属性转换为int

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

2

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

这会生成一个 List<Order>,而不是 List<int> - Guffa
现在它是一个 List<int?>,而不是一个 List<int> - Guffa

-1

有用的辅助/扩展方法:

我通常使用一些辅助扩展方法来完成其他答案中提到的工作:

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

针对不想在转换时简单忽略 null 值的读者

值得一提的是,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();

对于给我点踩的人:任何解释都会被欣赏,这样我就可以改进我的回答。 - Pac0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接