首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于LINQ的一个有关问题!疑点看红色字体这行

2012-12-31 
关于LINQ的一个问题!疑点看红色字体这行!using Systemusing System.Collections.Genericusing System.Li

关于LINQ的一个问题!疑点看红色字体这行!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq1
{
    public class linq2
    {
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string emailaddress { get; set; }
        public override string ToString()
        {
            return string.Format("{0} {1}\nemail: {2}", firstname, lastname, emailaddress);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<linq2> customers=createcustomerlist();
            IEnumerable<linq2> result = from customer in customers where customer.firstname == "donna" select customer;
            Console.WriteLine("firstname=="donna"");
                foreach(linq2 customer in result)
                {
                Console.WriteLine(customer.ToString());
                }
                customers[3].firstname = "donna";//为什么这里赋值后,result这个变量也改了呢!是不是又自动执行了上面Ienumerable<linq2>这行;                Console.WriteLine("firstname="donna"(take two)");
           
                foreach (linq2 customer in result)
                {
                    Console.WriteLine(customer.ToString());
                }
        }
        private static List<linq2> createcustomerlist()
        {
        List<linq2> customer5=new List<linq2>
        {
        new linq2{firstname="orlando",lastname="gee",emailaddress="orlando@adventure.com"},
        new linq2{firstname="donna",lastname="carreras",emailaddress="donna@adventure.com"}
        ,new linq2{firstname="bb166",lastname="qiu",emailaddress="donna@adventure.com"}


        ,new linq2{firstname="jbqiu",lastname="qiujianbin",emailaddress="qq@adventure.com"}
        ,new linq2{firstname="jbqiu168",lastname="qiujianbin168",emailaddress="qq168@adventure.com"}
        };
            return customer5;
        }
    }
}

[解决办法]
            List<int> numbers = new List<int>() { 1, 2 };
            IEnumerable<int> query = numbers.Select(i => i * 10).ToArray();
            numbers.Add(3);
            foreach (var item in query)
            {
                Console.WriteLine(item);//输出:10,20
            }

            numbers.Clear();//清空numbers集合
            foreach (var item in query)
            {
                Console.WriteLine(item);//输出:10,20
            }
要避免linq查询表达式的这个特性可以在查询语句后调用一下方法语法的查询
查询表达式都有重复执行、延迟执行的特性,而方法语法就会立即执行。
[解决办法]
延迟执行(使用的时候才会执行)
关于LINQ的一个有关问题!疑点看红色字体这行

这是我看Linq资料里提及相当频繁的一点.
[解决办法]
你将这句:
   IEnumerable<linq2> result = from customer in customers where customer.firstname == "donna" select customer;
修改成这样,就不会跟着变了:
   List<linq2> result = (from customer in customers where customer.firstname == "donna" select customer).ToList();

这不就是LINQ的延迟查询特性么...

热点排行