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