I am using Linq to Entities.
Have an entity \"Order\" which has a nullable column \"SplOrderID\".
I query my Orders list as
List
I usually use some helper extensions method for the jobs mentioned in the other answers :
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);
}
}
Usage in your case :
// 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);
It's worth mentioning the potential use of GetValueOrDefault(defaultValue)
yet, maybe you do you want to keep your original null values, but convert them to some default / sentinel value. (given as the defaultValue
parameter) :
For your example :
// 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();
linq
var lst = (from t in Orders
where t.SplOrderID.HasValue
select new Order
{
SplOrderID = t.SplOrderID
}).Select(c => c.SplOrderID.Value).ToList();
or
var lst = (from t in Orders
where t.SplOrderID.HasValue
select t.SplOrderID.Value).ToList();
I found your question trying resolve the same problem, and after a few tries, i got this solution, cast int
for each property on the list created by select
List<int> lst = Orders.where(u=> u.SplOrderID != null).Select(u => (int)u.SplOrderID);
As you are selecting the property, just get the value of the nullable:
List<int> lst =
Orders.Where(u => u.SplOrderID != null)
.Select(u => u.SplOrderID.Value)
.ToList();