Search code examples
c#entity-frameworklinqlinq-to-sqllinq-to-entities

Linq orderby same field different value


I have this query:

investorData = from investor in db.Investors
               join loanapp in db.LoanApplications on investor.FundID equals loanapp.FundID into loanAppData
               from lapp in loanAppData.DefaultIfEmpty()
               join fundreport in db.FundReportLoanDatas on lapp.LoanId equals fundreport.LoanId into fundReportData
               from freport in fundReportData.DefaultIfEmpty()
               where investor.FundID == fundID
               orderby lapp.LoanId descending
               select new InvestorPortfolioVM()
               {
                   InvestorId = investor.InvestorID,
                   CurrentLTV = freport.CurrentLTV == null ? 0.0 : freport.CurrentLTV,
                   LoanId = lapp.LoanId,
                   SegLTV = freport.SegLTV == string.Empty ? "" : freport.SegLTV,
                   BorrowerName = lapp.BorrowerName,
                   LoanStatusId = lapp.LoanStatusId
               };

What I want to achieve now is to order the items by one field, LoanStatusId beginning with loans which don't have LoanStatusId of 4 or 8.

Any idea how I can achieve that?


Solution

  • I think this will do what you want.

    investorData = from investor in db.Investors
                   join loanapp in db.LoanApplications on investor.FundID equals loanapp.FundID into loanAppData
                   from lapp in loanAppData.DefaultIfEmpty()
                   join fundreport in db.FundReportLoanDatas on lapp.LoanId equals fundreport.LoanId into fundReportData
                   from freport in fundReportData.DefaultIfEmpty()
                   where investor.FundID == fundID
                   orderby (lapp.LoanId >= 4 &&  lapp.LoanId <= 8) ? 1 : 0
                   select new InvestorPortfolioVM()
                   {
                       InvestorId = investor.InvestorID,
                       CurrentLTV = freport.CurrentLTV == null ? 0.0 : freport.CurrentLTV,
                       LoanId = lapp.LoanId,
                       SegLTV = freport.SegLTV == string.Empty ? "" : freport.SegLTV,
                       BorrowerName = lapp.BorrowerName,
                       LoanStatusId = lapp.LoanStatusId
                   };