How to change value without new projection in LINQ?

I have the following LINQ query:

var source = from node in MyNods
             select new
             {
                 Id = node.Id,
                 Name = node.Name,
                 ParentId = node.ParentId, // Nullable
             };

In the request above, ParentIdit is NULL. Now I need a new result that matches the first, but with a slight change, if ParentIdnull, I want it to be 0.

I wrote this:

var source2 =  from s in source
               select new
               {
                    Id = s.Id,
                    Name = s.Name,
                    ParentId = s.ParentId ?? 0, // Just change null values to 0
               };

Is it possible to implement this in a simpler way (I mean without a new projection)?

Edit : The new projection is the same for the first, and both ParentIdare null.

+3
source share
1 answer

LINQ is not ideal for performing side effects for an existing collection. If this is what you want to do, you would be better off:

foreach(var node in MyNods)
{
   if(!node.ParentId.HasValue) 
      node.ParentId = 0;
}

, . ; , , :

var source2 =  from s in source
               select new
               {
                    s.Id, s.Name,
                    ParentId = s.ParentId ?? 0
               };

EDIT: , (.. , , , ), . , "" ( ) , , , - . :

var source2 = source.Select(s => s.ToNonNullableParentVersion());

EDIT: , , "coalesced" nullable. , , .

+4

All Articles