日期:2014-05-17  浏览次数:21161 次

如果理解EF中的Lambda表达式?
using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Data.Entity.ModelConfiguration;
 
 namespace EFCodeFirstWalkthroughModel
 {
     public class BookConfiguration : EntityConfiguration<Book>
     {
        public BookConfiguration()
        {
             this.HasKey(b => b.ISBN);
             this.Property(b => b.Title).IsRequired();
             this.HasRequired(b => b.Author).WithMany(a => a.Books);
         }
     }
 }


例如上述代码之中,使用了Lambda表达式:  this.HasKey(b => b.ISBN); 
此处,b的值是由谁赋予的?在什么时候赋值?

另外在百度上找了一些解释例子,Lambda表达式相当于匿名委托,更加看不明白了,下面s是怎么赋值的?


var inString = list.FindAll(delegate(string s) {return s.Indexof("YJingLee") >= 0; });
使用Lambda表达式代码
var inString = list.FindAll(s => s.Indexof("YJingLee") >= 0);
Lambda表达式格式为:(参数列表)=>表达式或语句块



lambda

------解决方案--------------------
写一个FindAll的模拟代码帮助你理解:

List<string> FindAll(List<string> data, Func<string, bool> where)
{
    List<string> result = new List<string>();
    foreach (string item in data)
    {
        if (where(item))
            result.Add(item); //注意item是where的实参
    }
    return result;
}

调用
List<string> data = new List<string>() { "1", "1", "2", "2" };
List<string> result = FindAll(data, x => x == "1"); // result: "1" "1",注意x是过滤条件的形参。它哪里来的?FindAll调用它的时候把item作为参数传过来的。
------解决方案--------------------
接触不多,我以前理解成select ISBN from table b
我也说不清楚。