如何为此SQL查询编写Lambda表达式?

时间:2012-08-13 06:35:23

标签: c# lambda

我有以下SQL query

   Select cLedgerName,dDateFrom,cPeriodType,nPeriodFrom,nPeriodTo
   from sys_Account_Ledger a,sys_Log_Deposits_Interest_Master b
   where a.cGLCode=b.cGLCode and b.dDateFrom='08-11-2012' and b.cPeriodType='Days'  

我想用query来写Lambda expression。这就是我被困住的地方。

public IList<ListViewData> GetDepositsListViewData(string glCode, string effectDate, string periodType)
        {
            using (var db = new DataClasses1DataContext())
            {
                var data=db.sys_Account_Ledgers.Join(db.sys_Log_Deposits_Interest_Masters,
                    ledger=>ledger.cGLCode,
                    deposits=>deposits.cGLCode,
                    (ledger,deposits)=>new {db.sys_Account_Ledgers =ledger,db.sys_Log_Deposits_Interest_Masters =deposits}) 
            }
        }

我创建了一个class,它将是我查询的返回类型。

以下是class

public class ListViewData
        {
            public string LedgerName { get; set; }
            public string DateFrom { get; set; }
            public string PeriodType { get; set; }
            public int PeriodFrom { get; set; }
            public int PeriodTo { get; set; }
        }

任何人都可以帮我解决lambda expression吗?

2 个答案:

答案 0 :(得分:1)

var result = dataContext.SysAccountLedger
                        .Join(dataContext.SysLogDepositsInterestMaster,
                             a => a.cGlCode,
                             b => b.cGlCode,
                             (a, b) => new ListViewData
                             {
                                 LedgerName = a.LedgerName,
                                 DateFrom = b.DateFrom,
                                 PeriodType = b.PeriodType
                                 // other properties
                             })
                         .Where(item => item.DateFrom = Convert.ToDateTime("08-11-2012") && 
                                            item.PeriodType == "Days")
                         .ToList();

答案 1 :(得分:1)

//Direct translation into Linq:

    var query = from a in db.sys_Account_Ledger
        join b in db.sys_Log_Deposits_Interest_Master on a.cGLCode equals b.cGLCode
        where b.dDateFrom == Convert.ToDateTime("08-11-2012") && b.cPeriodType == "Days"
        select new { a, b };

//Lambda of this:

var query = db.sys_AccountLedger
    .Join(db.sys_Log_Deposits_Interest_Master, 
        a => a.cGLCode, 
        b => b.cGLCode, 
        (a, b) => new {a , b})
    .Where(w => w.dDateFrom == Convert.ToDateTime("08-11-2012") && w.cPeriodType == "Days");