문제

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

도움이 되었습니까?

해결책

Rewrite it as:

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

다른 팁

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. :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top