C#LINQ:从数组中删除空值并返回非空值

问题描述:

我正在将可为空的数组转换为不可为空的数组.这是我当前的代码,其中包含两个函数调用:

I'm converting nullable array to unnullable. This is my current code with two function calls:

myarray.Where(e => e.HasValue).Select(e => e.Value)

这看起来是非常基本的操作.一次通话就可以做到吗?

It looks like a very basic operation. Is it possible to do that in one call?

您始终可以进行自己的扩展,但是仅会使您的代码看起来更简洁,请认为您的实现是最简洁明了的你可以得到说实话

You can always make your own extensions but that only makes your code seem more succinct, think that your implementation is the most succinct and clear you can get to be honest

public static IEnumerable<T> GetNonNullValues<T>(this IEnumerable<Nullable<T>> items) where T: struct
{
    return items.Where(a=>a.HasValue).Select(a=>a.Value);
}