3

I have to do conditional joining between two tables Price and Operator

Table Prices

  1. CustomerName
  2. UnitPrice
  3. Country
  4. Code

Table Operators

  1. OpertorName
  2. Country
  3. Code

Joining requires to be run on following two conditions:

a. If Code is null for a record in table Prices then join only on basis of Country (all Codes of selected Country will be included from table Operators)

b. If Code is present for a record in table Prices then join on basis of both Country and Code

Please help

//If Code is null in table Price for a record then :

 var reportList = (from pl in Prices
                          join ml in Operators 
                          on pl.Country equals ml.Country                          
                          select new PriceReports {  }

//If Code is present in table Price for a record then 

    var reportList = (from pl in Prices
                          join ml in Operators 
                          on new { a = pl.Country, b = pl.MNC } equals new { a = ml.Country, b = ml.Code }
                          select new PriceReports {  }

I want to create a single query to represent both above conditions

1 Answer 1

3

You cannot write joins like this with the used join syntax in LinQ, you need to use a cross join with where conditions.

var reportList = from pl in PriceS
                 from ml in Operators.Where(mList => mList.Country == pl.Country
                                                   && (pl.Code == null || mList.Code == pl.Code))
                 select new PriceReports {  }
Sign up to request clarification or add additional context in comments.

4 Comments

will this approve both conditions?
@NextOlive It joins the table with the condition given in the where-function. In this case the same (CountryRegion.)Name/Country and Code is null OR same Code/MNC.
it is picking only the not null records (the second condition)
@NextOlive You were right, I checked for Code== null in the Operators data, you needed it in the prices data. I fixed it and also changed the MNC-Property to Code as described in your table definition (in opposing to MNC in your sample).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.