huysentruitw
huysentruitw

Reputation: 28141

Select result of where clause

Take this method f.e.:

public static Function Parse(string codeAndData)
{
    return (from factory in factories
            where factory.Parse(codeAndData) != null
            select factory.Parse(codeAndData)).FirstOrDefault();
}

As you can see, factory.Parse(codeAndData) is called twice, which is bad practice. Therefore we could write it like this:

public static Function Parse(string codeAndData)
{
    Function function = null;
    return (from factory in factories
            where (function = factory.Parse(codeAndData)) != null
            select function).FirstOrDefault();
}

But the above doesn't seem very elegant to me. Is there a better LINQ alternative to this?

Upvotes: 0

Views: 45

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477220

Instead of using assignments, you can do the selection procedure before:

public static Function Parse(string codeAndData) {
    return (from factory in factories
            select factory.Parse(codeAndData)
            ).Where(y => y != null).FirstOrDefault();
}

Upvotes: 1

JLRishe
JLRishe

Reputation: 101738

This is easy with the method chaining syntax:

return factories.Select(f => f.Parse(codeAndData))
                .FirstOrDefault(p => p != null);

With the comprehension syntax, you can accomplish this with let:

return (from factory in factories
        let p = factory.Parse(codeAndData)
        where p != null
        select p).FirstOrDefault();

Since you're already mixing FirstOrDefault with the comprehension syntax, you could also do this:

return (from factory in factories
        select factory.Parse(codeAndData))
       .FirstOrDefault(p => p != null);

but that seems kind of a silly alternative to the first option.

Upvotes: 3

Related Questions