Using 'out' in Linq query

186 views Asked by At

I am working with a List of Component objects, componentList.

Component has method GetPosition which returns position of a component via component.GetPosition(out position, out orientation). I can get X, Y, Z via position.X, position.Y, position.Z.

I have a separate List<CSVPart> imported from a CSV file. Each list item also has X, Y, Z. I want to find Component which matches X, Y, Z from the list of CSV parts.

I have tried:

foreach (CSVPart p in csvParts)
{
    foundComponent = componentList
        .Where(c => c.Name == p.PartNumber & ... == p.X & ... == p.Y & ... == p.Z
        )
}

Where Name corresponds to PartNumber and ... corresponds to me staring blankly at the screen. I've tried nesting the subsequent statements to compare X, Y, Z in {} but nothing I've tried worked. How do I get the out results into this Linq query? Thanks in advance for help.

1

There are 1 answers

0
Jon Skeet On BEST ANSWER

I would suggest you don't try to do it in a single expression. Instead, either write a method that does the matching you want and refer to that in your query, or use a block-bodied lambda:

foreach (CSVPart p in csvParts)
{
    var foundComponent = componentList.FirstOrDefault(c =>
    {
        // Avoid finding the position if the name doesn't match.
        if (c.Name != p.PartNumber)
        {
            return false;
        }
        c.GetPosition(out var position, out var _);
        return position.X == p.X && position.Y == p.Y && position.Z == p.Z;
    });
    // foundComponent will be null or the first match
}

(I've changed from Where to FirstOrDefault as the name suggests you're trying to find a single value...)