how to prevent the adding null indexes into a object using linq RRS feed

  • Question

  • User430178104 posted


    In my below query i am trying to fill a MyDocument object only the request pages object array contains a values, but if the request pages object has only one in that case my MyDocument object is creating two indexes, one is with value and other one is null. how to prevent the adding null indexes into MyDocument object. 

    below is my code

    var MyDocument = request.Pages != null
                        ? new[]
                            request.Pages.Count > 0
                                ? new Page1
                                    PageType = request.Pages[0].PageType
                                : null,
                            request.Pages.Count > 1
                                ? new Page1
                                    PageType = request.Pages[1].PageType
                                : null
                        : null;

    Tuesday, March 1, 2016 7:59 AM


  • User303363814 posted

    Is request.Pages ever null?  I'm assuming it is not.

    var MyDocument = request.Pages.Take(2).Select(p => new Page1 { PageType = p.PageType});

    (you can put .ToArray() on the end if you really, really need it.  My advice - avoid arrays)

    If request.Pages never has more than 2 elements then you can remove the .Take(2) clause.

    If request.Pages really could be null and you want the result to be null rather than a structure with no entries (probably a bad idea) then

    var MyDocument = request.pages == null ? null : otherwise as above

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 1, 2016 9:06 AM