Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert int array to nullable int array without looping over the elements?

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.

like image 528
Mohamad Haidar Avatar asked Sep 22 '15 22:09

Mohamad Haidar


1 Answers

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.

like image 177
StriplingWarrior Avatar answered Oct 17 '22 15:10

StriplingWarrior