C#课后小试6

LINQ可以很方便的对数据源进行筛选、排序和分组操作。

   格式 :from   ……      例:          from customer(范围变量) in customers(数据源)

           where  ……                      where customer.Firstname=="sadas"  (筛选的条件)

            select  ……                     select customer     (映射,具体要选的主体或属性)

LINQ查询式可以立刻执行

foreach (Customer customer in result) {……;}

customers[3].FirstName = "Donna";

foreach (Customer customer in result){…;}  rusult将立刻改变

如果不想改变,可以预存变化前的值,可以使用tolist() toarry()

 static void Main()

 {

   List<Customer> customers = CreateCustomerList();

   IEnumerable<Customer> result = from customer in customers

      where customer.FirstName == "Donna“ select customer;

 

    List<Customer> cachedResult = result.ToList<Customer>();   //存值,需要之前的值就去查之前存的地方。

 

    foreach (Customer customer in cachedResult){…;}

    customers[3].FirstName = "Donna";

    Console.WriteLine("FirstName == \"Donna\" (take two)");

    foreach (Customer customer in cachedResult){…;}

}

 

连接 join

 [data source 1] join [data source 2] on [join condition]

将两个数据源按照一定条件连接在一起

customer in customers join address in addresses on customer.Name equals address.Name;

排序 orderby

var result =from customer in Customers

                orderby customer.LastName

                 select customer;  //升序排Lastname中数据

var 关键字能够代替局部变量的类型

     foreach (var ca in result) //

     {

         Console.WriteLine(string.Format("{0}\nAddress: {1}",

             ca.Customer, ca.Address));

      }

 

分组 group

var result = from address in addresses

      group address by address.Name;//按照条件 address.Name 分组

foreach (var gp in result)

{

      Console.WriteLine("{0}", gp.Key); //~.key代表分组条件,即address.Name

       foreach (var a in gp)

             Console.WriteLine("\t{0}", a);

 }

 

posted @ 2015-04-27 20:30  我是文小浩  阅读(106)  评论(0编辑  收藏  举报