简体   繁体   中英

C# LINQ: remove null values from an array and return as not nullable

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?

myarray.OfType<int>();

这是有效的,因为如果它们不为空,可空类型会框到它们的基础类型,但如果它们为空,则不会。

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

try using .OfType(...)

Example...

myarray.OfType<int>()

... this worked for me ...

var d = new int?[] { 1, 2, 3, 4, 5, null, null, 6, 7, 8, 9, null };
Console.WriteLine(d.Count()); // 12
Console.WriteLine(d.OfType<int>().Count()); //9

试试这个:

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

Your expression is as pretty as it can get, and thanks to how the Enumerables are looped through, your collection won't technically be visited twice in two separate loops.

If you still want to do it in a single expression, here is one of the many ugly ways.

myarray.Aggregate(Enumerable.Empty<YourElementType>(), (prev, next) => next.HasValue? prev.Concat(new [] { next }) : prev);

The above should never be used and it is only for demonstration purposes. I would use what you wrote in your question, yours is prettier.

While .OfType<> solution works, the intent is not quite clear there, I suggest this solution that is pretty much the same that the solution in the question, but it allows compiler and eg R# to be sure in the output type and not have a warning for a possible null reference exception (for eg nullable objects in C# 8).

myarray
  .Where(e => e != null)
  .Select(e => e ?? new Exception("Unexpected null value"))

This seems like a bit overkill, and can be fixed with eg "e!", but it's a bit more secure against future errors (if eg where clause is modified by mistake)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM