将List 隐式转换为List

我正在使用Linq to Entities。

有一个实体“Order”,它有一个可为空的列“SplOrderID”。

我查询我的订单列表

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

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

我只是期待LINQ有点聪明。

我该怎么处理?

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

 List 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创建的列表中的每个属性转换为int

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

有用的帮助/扩展方法:

我通常对其他答案中提到的作业使用一些辅助扩展方法:

 public static class IEnumerableExtensions { public static IEnumerable GetNonNull(this IEnumerable source, Func 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 or List etc... public static IEnumerable GetNonNull(this IEnumerable source) where T : struct { return GetNonNull(source, x => x); } public static IEnumerable GetNonNull(this IEnumerable 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 lst = Orders.GetNonNull(u => u.SplOrderID); 

对于不希望在转换时简单地忽略空值的读者

值得一提的是GetValueOrDefault(defaultValue)的潜在用途,也许您希望保留原始的空值,但将它们转换为某个默认值/ sentinel值。 (作为defaultValue参数给出):

对于你的例子:

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