Question

Is there a better way of writing this? I dont like the way the null check is in there

    editItem.FrameVent =fd.FirstOrDefault(x => x.hardwaretype == 39 
&& x.name.StartsWith("Frame Vent"))==null?null: fd.FirstOrDefault(x => x.hardwaretype == 39 
&& x.name.StartsWith("Frame Vent")).hardwareid;

I could do without repeating the query bit

Était-ce utile?

La solution

Rewrite it as:

editItem.FrameVent = fd.Where(x => x.hardwaretype == 39 && x.name.StartsWith("Frame Vent"))
                       .Select(p => p.hardwareid)
                       .FirstOrDefault();

Autres conseils

You could also do it a bit more classic:

var result = fd.FirstOrDefault(x => x.hardwaretype == 39 && x.name.StartsWith("Frame Vent"));
editItem.FrameVent = result == null ? null : result.hardwareid;

You can add a variable to simplify

var frameVent = fd.FirstOrDefault(x => x.hardwaretype == 39 && x.name.StartsWith("Frame Vent"));
editItem.FrameVent = frameVent==null ? null : frameVent.hardwareid;

Just as some extra information, rather than an answer:

If Microsoft do get around to implementing the "Safe Navigation Operator" ('?.') (as requested here), then the solution would look like this:

editItem.FrameVent =
    fd.FirstOrDefault(x => x.hardwaretype == 39 && x.name.StartsWith("Frame Vent"))
    ?.hardwareid;

Whether or not introducing this new operator would be a good idea is a matter for debate. :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top