Search code examples
c#linqlambdaanonymous-methods

Replacing a regular method with an anonymous method in C#/LINQ


I have a LINQ query that looks like this:

public IEnumerable<Foo> SelectFooBars()
{
    return
        from
            f in foos
        join
            b in bars
            on f.BarId equals b.Id
        select
            AddMissingProp(f, b.MissingProp);
}

public void AddMissingProp(Foo foo, string missingProp) // substitute this with inline lambda
{
    foo.MissingProp = missingProp;
    return foo;
}

I would like to get rid of AddMissingProp and use some form of a lambda in my select clause instead.

I attempted...

...
select
    (f, b) => { f.MissingProp = b.MissingProp; return f }

...but I got the following error:

A local variable named 'f' cannot be declared in this scope because it would give a different meaning to 'f', which is already used in a 'parent or current' scope to denote something else.

How can I "lambda-ize" my query?


Update

This also doesn't work:

...
select
    () => { f.MissingProp = b.MissingProp; return f }

I get the following error:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

I didn't change the join clause at all, so I'm perplexed.


Solution

  • You can give types to your parameters in a lambda expression but you need to use different names since you're already using f and b in the query.

    (Foo f1, Bar b1) => ...

    Edit

    return
    (
        from 
            f in foos 
        join
            b in bars 
            on f.BarId equals b.Id 
        select 
            new {f, b}
    ).select(foobar => {foobar.f.BarId = foobar.b.Id; return foobar.f});