I have a number of int? elements int? . Suppose this:
int?[] row = new int?[] {0,null,1,2,3,0}; It is necessary for all elements that are equal to zero to create a certain structure (Suppose with the element index), discard the rest. The logic is something like this:
MyStruct[] ar = row.Select( (el, ind) => el == 0 ? new MyStruct {index = ind} : null ) That is, for all zero elements we create a structure, for all the others we return null . Next, just filter out non-null elements, and turn everything into an array
.Where(el => el != null).ToArray(); In the conditional line, an error is received:
Cant be no conditional conversion between Test.MyStruct and null
How to do right? May use a different approach? I want to use LINQ and not cycles.
Full text of the program
using System; using System.Linq; public class Test { struct MyStruct { public int index; } public static void Main() { int?[] row = new int?[] {0,null,1,2,3,0}; MyStruct[] ar = row.Select( (el, ind) => el == 0 ? new MyStruct {index = ind} : null ).Where(el => el != null).ToArray(); } } or here
Whereand put it toSelect, then the index of the element in the source array will be lost. If you pull the structure into a heap (convert to a class), it will not be very beautiful. The variant withdynamicalso seems not too beautiful. How is more correct? - user200141