Useful helper / extension method :
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);
For the readers who don't want to simply ignore null values while converting
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();