how to convert int array
to nullable int array
without looping over the elements?
project.Suppliers = project.ProjectSuppliers.Select(proj => proj.ProjectSupplier).ToArray();
in the above code I am trying to assign project.ProjectSuppliers.Select(proj => proj.ProjectSupplier).ToArray();
to the nullable array project.Suppliers
but I can't because it is nullable so what is the best way to do this without looping over the elements one by one.
Two options:
Cast the items in your Select statement:
project.Suppliers = project.ProjectSuppliers
.Select(proj => (int?)proj.ProjectSupplier)
.ToArray();
Use Cast<>()
:
project.Suppliers = project.ProjectSuppliers
.Select(proj => proj.ProjectSupplier)
.Cast<int?>()
.ToArray();
The first option will probably have slightly better performance when using LINQ to Objects, and it'll probably have fewer surprises. (Some types use overloaded operators for explicit casts in code, but Cast<>()
will throw an exception for the same conversion because its internal code doesn't know what those types are at compile time.)
The second option is more concise when you've got a precomposed IEnumerable<>
or IQueryable<>
and you don't want to create a whole Select()
statement just for this purpose.
I should also note that when you're using LINQ to Objects, both of these will iterate over the given collection. You cannot convert an array of one type to an array of another type in C#, because at run-time each array instance is aware of what type of object it's holding and how much space each of those objects are going to need. These methods just give you a nice chainable syntax, rather than requiring a for
loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With