user2041189
user2041189

Reputation: 73

Where clause on Linq Extension method

I have the following lambda expression:

query = query.Join( SecondTableSource,
table1 => new
{
    table1 .Field1,
    table1 .Field2
},
table2 => new
{
    table2 .Field1,
    table2 .Field2
},
( table1 , table2 ) => table1 ) ;

As you can see I am only returning results from the first table but I need to filter out results by a column in table2. How would I go about doing that but still only returning IQueryable<table1>?

Thanks!

Here is the original code I am trying to convert:

query = from table1 in Model.Table1s
    join table2 in Model.Table2s
        on new
        {
            table1.field1,
            table1.field2
        }
    equals
        new
        {
            table2.field1,
            table2.Part
        }
    where table2.field.StartsWith( criteria.value )
    select table1;

I think I must not have converted correctly because the first two answers posted (that is all that is posted at the time i am writing this) should work but both only return one result when I am expecting 4 (as was returned by original query).

Upvotes: 1

Views: 606

Answers (2)

TylerOhlsen
TylerOhlsen

Reputation: 5578

Here's another option if you have a more complicated query...

IEnumerable<MyType1> result = table1.Join(table2,
        t1 => new { t1.Field1, t1.Field2 },
        t2 => new { t2.Field1, t2.Field2 },
        (t1, t2) => new { table1 = t1, table2 = t2 }).
    Where(joinedResults => joinedResults.table2 == //condition).
    Select(filteredResults => filteredResults.table1);

Upvotes: 0

C&#233;dric Bignon
C&#233;dric Bignon

Reputation: 13022

Filter the table2 before can't you?

query = query.Join(SecondTableSource.Where(table2 => table2.MyFieldToFilter == condition),
                   table1 => ...,
                   ...);

Upvotes: 2

Related Questions