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

夙愿已清 提交于 2021-01-27 05:47:39

问题


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?


回答1:


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



回答2:


myarray.OfType<int>();

This works because nullable types box to their underlying types if they are not null, but don't if they are null.




回答3:


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



回答4:


Try this:

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



回答5:


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.




回答6:


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 e.g. R# to be sure in the output type and not have a warning for a possible null reference exception (for e.g. 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 e.g. "e!", but it's a bit more secure against future errors (if e.g. where clause is modified by mistake)



来源:https://stackoverflow.com/questions/38381612/c-sharp-linq-remove-null-values-from-an-array-and-return-as-not-nullable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!