Lambda Expression in C#

來源:互聯網
上載者:User

標籤:

1、Expression

    Expression<Func<double, double>> exp = a => Math.Sin(a);

    委託類型Func<double, double>,它限定產生的運算式樹狀架構是一個接受double,並返回double的一元Lambda函數

 <Func<double, double, double, double, double> 輸入參數為4個double,返回一個double類型
  static void Main(string[] args)    {        Expression<Func<double, double, double, double, double>> myExp =            (a, b, m, n) => m * a * a + n * b * b;        var calc = new BinaryExpressionCalculator(myExp);        Console.WriteLine(calc.Calculate(1, 2, 3, 4));    }

2、在linq to sql中的使用

     LoadWith方法,輸入類型為泛型T,輸入參數為Expression,返回System.Linq.Expressions.LambdaExpression

     LoadsWith方法,接受LambdaExpression[],載入資料

  <Func<T, object> 輸入泛型,返回object(因為傳回型別未定,所以為object)
    public partial class Db   //為Db.dbml檔案的partial class 
    {

        public static LambdaExpression LoadWith<T>(Expression<Func<T, object>> expression)
        {
            return expression;
        }
       
        public void LoadsWith(params LambdaExpression[] expressions)
        {
            var dlo = new DataLoadOptions();
            foreach (var expression in expressions)
            {
                dlo.LoadWith(expression);
            }
            LoadOptions = dlo;
        }

           public static Db Open(bool readOnly = false) {

      var db = new Db();

      if (readOnly) db.ObjectTrackingEnabled = false;

       return db;

    }
    }

MSDN上對LoadWith的解釋是:通過使用 lambda 運算式檢索與主目標相關的指定資料。 LoadWith可以用一個sql語句載入相關表的資料

例如Student表inner join Class表,這就是LoadWith的意義所在。

調用:

 using (var db = Db.Open()) {        db.LoadsWith(          Db.LoadWith<Project>(p => p.Client),           Db.LoadWith<Project>(p => p.Files)        );        var project = db.Projects.SingleOrDefault(p => p.Id == form.Id);}

 

Exploring Lambda Expression in C#

Expression Tree上手指南

https://msdn.microsoft.com/en-us/library/bb397687.aspx

巧用Expression運算式 解決類似於sql中 select in 的查詢(適合於中小型項目)

linq to sql

 

 

Lambda Expression in C#

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.