Order List with LINQ while omitting unwanted entries?

Hey there,
I was wondering if I could use a LINQ Statement to get the closest entry from a list of objects, that is also matching another requirement.
To get the closest object, I’m using this statement:

private Builder GetClosestBuilder()
{
    return BuildingManager.Instance._builders
        .OrderBy(x => Vector3.Distance(x.transform.position, this.transform.position)).ToList()[0];
}

Is there a possibility to add something like a WHERE clause right into it or do i need to separate these steps?
In this example, I want to find the closest builder that is not busy (builder.busy == false)

I think I’ve got it:

    private Builder GetClosestBuilder()
    {
        return BuildingManager.Instance._builders
            .Where(x => !x.Busy).OrderBy(x => Vector3.Distance(x.transform.position, this.transform.position)).ToList()[0];
    }

Still, is there a way to get this line shorter?

length of the line does not matter, but yeah that would be the right way. since you are only doing this to get the first element. you could drop the ToList, and replace OrderBy with a FirstOrDefault which will return you the element directly instead of a IEnumerable

1 Like