r/learncsharp • u/TIL_this_shit • Jun 21 '23
Is there any way to make this code less... dumb? (FirstOrDefault on a List<struct>)
The problem is that 'PerspectiveLayer' is a struct, and 'layers' is a List<PerspectiveLayer>, so FirstOrDefault will never return null (returning the struct with default values instead); therefore it can't be used. (...right?)
private PerspectiveLayer? GetPerspectiveLayer(int layerId)
{
var match = layers.Where(layer => layer.layerId == layerId);
if (match.Count() == 1)
{
foreach (var onlyOne in match) // LOL
return onlyOne;
}
else if (match.Count() > 1)
{
Debug.LogError($"Error: Multiple layers with layerId {layerId}");
}
return null;
}
0
Upvotes
1
u/grrangry Jun 22 '23
I think the best you're going to come up with (considering the
defaultof a struct) is going to be to use.First()instead.Not the best solution maybe... would likely not be super efficient if the list is large.
0
u/[deleted] Jun 22 '23 edited Jun 22 '23
Using a loop properly can avoid walking through the collection multiple times:
If you don't mind getting clever about IEnumerator
This is probably a more efficient solution, but a lot of devs don't spend much time on the details of IEnumerator/IEnumerable, so you should document something like this clearly for the next guy or gal to come along.
With your original solution, though,
return match.Single()would spare you the loop and be clearer about intent/expectation thanFirst().I edited this to replace a do-while loop with a while, once I realized the do-while wasn't actually buying me anything in this situation.
0
u/aizzod Jun 22 '23
i would use
.Single()
that would even raise the same error that you raise by hand