LINQ 基本知识

   1:  
   2: 1.1泛型
   3:  
   4: 目标:解决参数类型转换效率,利用泛型可以提高效率
   5: using System;
   6:  
   7: namespace DemoGeneric1
   8: {
   9:     /// <summary>
  10:     /// 泛型类
  11:     /// </summary>
  12:     public class GenericClass<T>
  13:     {
  14:         /// <summary>
  15:         /// 泛型类型的字段
  16:         /// </summary>
  17:         private T value;
  18:  
  19:         /// <summary>
  20:         /// 泛型类型的属性
  21:         /// </summary>
  22:         public T Value
  23:         {
  24:             get
  25:             {
  26:                 return value;
  27:             }
  28:         }
  29:  
  30:         /// <summary>
  31:         /// 带泛型参数的函数
  32:         /// </summary>
  33:         /// <param name="input"></param>
  34:         public void Add(T input) 
  35:         {
  36:             this.value = input;
  37:         }
  38:     }
  39:  
  40:     class Program
  41:     {
  42:         static void Main(string[] args)
  43:         {
  44:             //使用字符串类型
  45:             GenericClass<string> str = new GenericClass<string>();
  46:             str.Add("字符串测试");
  47:             Console.WriteLine(string.Format("Value 类型:{0}", str.Value.GetType().Name));
  48:             Console.WriteLine(string.Format("Value:{0}", str.Value));
  49:  
  50:             Console.WriteLine("******************************");
  51:  
  52:             //使用 int 类型
  53:             GenericClass<int> intc = new GenericClass<int>();
  54:             intc.Add(123456);
  55:             Console.WriteLine(string.Format("Value 类型:{0}", intc.Value.GetType().Name));
  56:             Console.WriteLine(string.Format("Value:{0}", intc.Value));
  57:  
  58:  
  59:             Console.ReadKey();
  60:         }
  61:     }
  62: }
  63:  
  64: 1.2 Arraylist 和List<T>
  65:  
  66: using System;
  67: using System.Collections.Generic;
  68: using System.Collections;
  69:  
  70: namespace DemoGeneric2
  71: {
  72:     class Program
  73:     {
  74:         static void Main(string[] args)
  75:         {
  76:             ArrayList arr = new ArrayList();
  77:             List<int> lst = new List<int>();
  78:  
  79:             //ArrayList 计时开始
  80:             DateTime dt = DateTime.Now;
  81:  
  82:             //将100万个元素加入ArrayList
  83:             for (int i = 0; i < 1000000; i++)
  84:                 arr.Add(i);
  85:  
  86:             //ArrayList 计时段
  87:             TimeSpan ts1 = DateTime.Now - dt;
  88:  
  89:             //List 计时开始
  90:             dt = DateTime.Now;
  91:  
  92:             //将100万个元素加入List
  93:             for (int i = 0; i < 1000000; i++)
  94:                 lst.Add(i);
  95:  
  96:             //List 计时段
  97:             TimeSpan ts2 = DateTime.Now - dt;
  98:  
  99:  
 100:             Console.WriteLine(string.Format("ArrayList 耗时:{0} ms", ts1.Milliseconds));
 101:             Console.WriteLine(string.Format("List<T> 耗时:{0} ms", ts2.Milliseconds));
 102:  
 103:             Console.ReadKey();
 104:         }
 105:     }
 106: }
 107:  
 108: 1.3
 109:  
 110: using System;
 111:  
 112: namespace DemoDelegate1
 113: {
 114:     /// <summary>
 115:     /// 定义一个没有返回类型的委托
 116:     /// </summary>
 117:     delegate void myDelgage(string s);
 118:     
 119:     /// <summary>
 120:     /// 定义一个有返回类型的委托
 121:     /// </summary>
 122:     delegate string myDelgageString(string s, bool man);
 123:  
 124:     class Program
 125:     {
 126:         /// <summary>
 127:         /// 没有返回的方法
 128:         /// </summary>
 129:         static void Show1(string s)
 130:         {
 131:             Console.WriteLine(string.Format("  你好, {0}!", s));
 132:         }
 133:         static void Show2(string s)
 134:         {
 135:             Console.WriteLine(string.Format("  早上好, {0}!", s));
 136:         }
 137:         static void Show3(string s)
 138:         {
 139:             Console.WriteLine(string.Format("  晚上好, {0}!", s));
 140:         }
 141:  
 142:         /// <summary>
 143:         /// 返回字符串的方法
 144:         /// </summary>
 145:         static string AddTitle(string s, bool man)
 146:         {
 147:             if (man)
 148:                 return string.Format("  你好, {0} 先生", s);
 149:             else
 150:                 return string.Format("  你好, {0} 女士", s);
 151:         }
 152:  
 153:         static void Main(string[] args)
 154:         {
 155:             string name = "林晚荣";
 156:             string name2 = "徐芷晴";
 157:  
 158:             //.NET 1.1 的委托实例化
 159:             myDelgage del1 = new myDelgage(Show1);
 160:             Console.WriteLine("  .NET 1.1 的委托调用");
 161:             del1(name);
 162:             Console.WriteLine("***********************************");
 163:  
 164:             //.NET 2.0 以上的委托实例化
 165:             myDelgage del2 = Show1;
 166:             Console.WriteLine("  .NET 2.0 以上的委托调用");
 167:             del2(name);
 168:             Console.WriteLine("***********************************");
 169:  
 170:             //多路委托绑定
 171:             Console.WriteLine("  多路委托绑定调用");
 172:             del2 += Show2;
 173:             del2 += Show3;
 174:             del2(name);
 175:             Console.WriteLine("\n  合并掉Show1委托调用");
 176:             del2 -= Show1;
 177:             del2(name);
 178:             Console.WriteLine("***********************************");
 179:  
 180:             //返回类型的委托
 181:             myDelgageString del3 = AddTitle;
 182:  
 183:             Console.WriteLine("  返回类型的委托调用");
 184:             Console.WriteLine(del3(name, true));
 185:             Console.WriteLine(del3(name2, false));
 186:  
 187:             Console.ReadKey();
 188:         }
 189:  
 190:         public event myDelgage myEvet;
 191:     }
 192: }
 193: 1.4 自定义事件及其事件数据类和利用代理跨线程的数据传递
 194: Public event EventHandler myEvent;
 195:  
 196: namespace DemoDelegate2
 197: {
 198:     partial class EventDemo
 199:     {
 200:         /// <summary>
 201:         /// 必需的设计器变量。
 202:         /// </summary>
 203:         private System.ComponentModel.IContainer components = null;
 204:  
 205:         /// <summary>
 206:         /// 清理所有正在使用的资源。
 207:         /// </summary>
 208:         /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
 209:         protected override void Dispose(bool disposing)
 210:         {
 211:             if (disposing && (components != null))
 212:             {
 213:                 components.Dispose();
 214:             }
 215:             base.Dispose(disposing);
 216:         }
 217:  
 218:         #region Windows 窗体设计器生成的代码
 219:  
 220:         /// <summary>
 221:         /// 设计器支持所需的方法 - 不要
 222:         /// 使用代码编辑器修改此方法的内容。
 223:         /// </summary>
 224:         private void InitializeComponent()
 225:         {
 226:             this.but = new System.Windows.Forms.Button();
 227:             this.progressBar = new System.Windows.Forms.ProgressBar();
 228:             this.SuspendLayout();
 229:             // 
 230:             // but
 231:             // 
 232:             this.but.Location = new System.Drawing.Point(172, 35);
 233:             this.but.Name = "but";
 234:             this.but.Size = new System.Drawing.Size(75, 23);
 235:             this.but.TabIndex = 0;
 236:             this.but.Text = "开始";
 237:             this.but.UseVisualStyleBackColor = true;
 238:             this.but.Click += new System.EventHandler(this.but_Click);
 239:             // 
 240:             // progressBar
 241:             // 
 242:             this.progressBar.Location = new System.Drawing.Point(12, 95);
 243:             this.progressBar.Name = "progressBar";
 244:             this.progressBar.Size = new System.Drawing.Size(235, 23);
 245:             this.progressBar.TabIndex = 1;
 246:             // 
 247:             // EventDemo
 248:             // 
 249:             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
 250:             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
 251:             this.ClientSize = new System.Drawing.Size(259, 149);
 252:             this.Controls.Add(this.progressBar);
 253:             this.Controls.Add(this.but);
 254:             this.Name = "EventDemo";
 255:             this.Text = "自定义事件演示";
 256:             this.ResumeLayout(false);
 257:  
 258:         }
 259:  
 260:         #endregion
 261:  
 262:         private System.Windows.Forms.Button but;
 263:         private System.Windows.Forms.ProgressBar progressBar;
 264:     }
 265: }
 266:  
 267: namespace DemoDelegate2
 268: {
 269:     partial class EventDemo
 270:     {
 271:         /// <summary>
 272:         /// 必需的设计器变量。
 273:         /// </summary>
 274:         private System.ComponentModel.IContainer components = null;
 275:  
 276:         /// <summary>
 277:         /// 清理所有正在使用的资源。
 278:         /// </summary>
 279:         /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
 280:         protected override void Dispose(bool disposing)
 281:         {
 282:             if (disposing && (components != null))
 283:             {
 284:                 components.Dispose();
 285:             }
 286:             base.Dispose(disposing);
 287:         }
 288:  
 289:         #region Windows 窗体设计器生成的代码
 290:  
 291:         /// <summary>
 292:         /// 设计器支持所需的方法 - 不要
 293:         /// 使用代码编辑器修改此方法的内容。
 294:         /// </summary>
 295:         private void InitializeComponent()
 296:         {
 297:             this.but = new System.Windows.Forms.Button();
 298:             this.progressBar = new System.Windows.Forms.ProgressBar();
 299:             this.SuspendLayout();
 300:             // 
 301:             // but
 302:             // 
 303:             this.but.Location = new System.Drawing.Point(172, 35);
 304:             this.but.Name = "but";
 305:             this.but.Size = new System.Drawing.Size(75, 23);
 306:             this.but.TabIndex = 0;
 307:             this.but.Text = "开始";
 308:             this.but.UseVisualStyleBackColor = true;
 309:             this.but.Click += new System.EventHandler(this.but_Click);
 310:             // 
 311:             // progressBar
 312:             // 
 313:             this.progressBar.Location = new System.Drawing.Point(12, 95);
 314:             this.progressBar.Name = "progressBar";
 315:             this.progressBar.Size = new System.Drawing.Size(235, 23);
 316:             this.progressBar.TabIndex = 1;
 317:             // 
 318:             // EventDemo
 319:             // 
 320:             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
 321:             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
 322:             this.ClientSize = new System.Drawing.Size(259, 149);
 323:             this.Controls.Add(this.progressBar);
 324:             this.Controls.Add(this.but);
 325:             this.Name = "EventDemo";
 326:             this.Text = "自定义事件演示";
 327:             this.ResumeLayout(false);
 328:  
 329:         }
 330:  
 331:         #endregion
 332:  
 333:         private System.Windows.Forms.Button but;
 334:         private System.Windows.Forms.ProgressBar progressBar;
 335:     }
 336: }
 337:  
 338:  
 339: using System;
 340:  
 341: namespace DemoDelegate2
 342: {
 343:     /// <summary>
 344:     /// 自定义的事件数据类
 345:     /// </summary>
 346:     public class MyEnentArgs : EventArgs
 347:     {
 348:         /// <summary>
 349:         /// 需要传递的数据
 350:         /// </summary>
 351:         public int Number { get; private set; }
 352:  
 353:         public MyEnentArgs(int n)
 354:         {
 355:             this.Number = n;
 356:         }
 357:     }
 358:  
 359: }
 360:  
 361: using System;
 362: using System.Collections.Generic;
 363: using System.Linq;
 364: using System.Windows.Forms;
 365:  
 366: namespace DemoDelegate2
 367: {
 368:     static class Program
 369:     {
 370:         /// <summary>
 371:         /// 应用程序的主入口点。
 372:         /// </summary>
 373:         [STAThread]
 374:         static void Main()
 375:         {
 376:             Application.EnableVisualStyles();
 377:             Application.SetCompatibleTextRenderingDefault(false);
 378:             Application.Run(new EventDemo());
 379:         }
 380:     }
 381: }
 382:  
 383:  
 384: using System;
 385: using System.Windows.Forms;
 386: using System.Threading;
 387:  
 388: namespace DemoDelegate2
 389: {
 390:     public partial class EventDemo : Form
 391:     {
 392:         /// <summary>
 393:         /// 定义事件
 394:         /// </summary>
 395:         public event EventHandler<MyEnentArgs> Half;
 396:  
 397:         /// <summary>
 398:         /// 定义一个用于更新界面的委托
 399:         /// </summary>
 400:         /// <param name="?"></param>
 401:         private delegate void UpdateCtlDelegate(int data, bool evt, bool over);
 402:  
 403:         public EventDemo()
 404:         {
 405:             InitializeComponent();
 406:  
 407:             //挂载事件处理函数
 408:             this.Half += new EventHandler<MyEnentArgs>(EventDemo_Half);
 409:         }
 410:  
 411:         /// <summary>
 412:         /// 自定义事件处理函数
 413:         /// </summary>
 414:         void EventDemo_Half(object sender, MyEnentArgs e)
 415:         {
 416:             MessageBox.Show(string.Format("参数数据:{0}", e.Number), "事件成功被引发");
 417:         }
 418:  
 419:         /// <summary>
 420:         /// 开始按钮Click事件处理
 421:         /// </summary>
 422:         private void but_Click(object sender, EventArgs e)
 423:         {
 424:             this.but.Enabled = false;
 425:             //启动工作线程
 426:             Thread th = new Thread(new ThreadStart(progress));
 427:             th.IsBackground = true;
 428:             th.Start();
 429:         }
 430:  
 431:         /// <summary>
 432:         /// 界面更新及事件引发
 433:         /// </summary>
 434:         private void update(int data, bool evt, bool over)
 435:         {
 436:             //检测是否需要返回界面线程
 437:             if (this.InvokeRequired)
 438:             {
 439:                 //通过委托返回界面线程
 440:                 this.BeginInvoke(new UpdateCtlDelegate(update), new object[] { data, evt, over });
 441:                 return;
 442:             }
 443:  
 444:             //循环结束修改Button显示
 445:             if (over)
 446:             {
 447:                 this.but.Enabled = true;
 448:                 return;
 449:             }
 450:  
 451:             if (evt)
 452:             {
 453:                 //引发事件
 454:                 this.Half(this, new MyEnentArgs(data));
 455:             }
 456:             else
 457:             {
 458:                 //更新进度条
 459:                 this.progressBar.Value = data;
 460:             }
 461:         }
 462:  
 463:         /// <summary>
 464:         /// 工作线程处理方法
 465:         /// </summary>
 466:         private void progress()
 467:         {
 468:             for (int i = 0; i < 100; i++)
 469:             {
 470:                 this.update(i, false, false);
 471:  
 472:                 if (i == 50)
 473:                 {
 474:                     if (this.Half != null)
 475:                         this.update(i, true, false);
 476:                 }
 477:  
 478:                 //延时
 479:                 System.Threading.Thread.Sleep(10);
 480:             }
 481:  
 482:             this.update(0, false, true);
 483:         }
 484:     }
 485: }
 486:  
 487: 5 迭代器与yield 关键字
 488: yield 关键字在迭代器中,用于向枚举对象返回元素值或发出迭代结束信号
 489:  
 490: yield return <expression>
 491: yield break
 492:  
 493: using System;
 494:  
 495: namespace DemoInitializer1
 496: {
 497:     class Girlfriend
 498:     {
 499:         public string Name { get; set; }
 500:         public int Age { get; set; }
 501:     }
 502:  
 503:     class Boy
 504:     {
 505:         public string Name { get; set; }
 506:         public int Age { get; set; }
 507:         public Girlfriend Girl{ get; set; }
 508:     }
 509:  
 510:     class Program
 511:     {
 512:         static void Main(string[] args)
 513:         {
 514:             //用对象初始化器创建对象
 515:             Girlfriend gf1 = new Girlfriend { Name = "秦仙儿",  };
 516:             
 517:             //等价于
 518:             Girlfriend gf2 = new Girlfriend();
 519:             gf2.Name = "萧玉若";
 520:             gf2.Age = 21;
 521:  
 522:             //用嵌套的对象初始化器创建对象
 523:             Boy boy1 = new Boy { Name = "林晚荣", Age = 24, Girl = new Girlfriend { Name = "肖青漩", Age = 20 } };
 524:  
 525:             //等价于
 526:             Boy boy2 = new Boy();
 527:             Girlfriend gf3 = new Girlfriend();
 528:  
 529:             gf3.Name = "董巧巧";
 530:             gf3.Age = 18;
 531:             boy2.Name = "林三";
 532:             boy2.Age = 24;
 533:             boy2.Girl = gf3;
 534:  
 535:             Console.WriteLine("gf1 初始化的类型:" + gf1.GetType().Name);
 536:             Console.WriteLine("boy1 初始化的类型:" + boy1.GetType().Name);
 537:  
 538:             Console.ReadKey();
 539:         }
 540:     }
 541: }
 542:  
 543:  
 544: 7 、隐式类型的局部变量 var
 545: var 类型的确定由初始化语句的右侧的表达式推断出来的
 546:  
 547:  
 548: using System;
 549: using System.Collections.Generic;
 550:  
 551: namespace DemoVar
 552: {
 553:     class Program
 554:     {
 555:         static void Main(string[] args)
 556:         {
 557:             var str = "测试字符串";
 558:             var i = 123456;
 559:             var lst = new List<string>();
 560:             var arr = new string[] { "大华军师", "金刀可汗", "圣坊仙子", "金陵才女" };
 561:  
 562:             Console.WriteLine(string.Format("变量 str 的数据类型:{0}", str.GetType().Name));
 563:             Console.WriteLine(string.Format("变量 i 的数据类型:{0}", i.GetType().Name));
 564:             Console.WriteLine(string.Format("变量 lst 的数据类型:{0}", lst.GetType().Name));
 565:             Console.WriteLine(string.Format("变量 arr 的数据类型:{0}", arr.GetType().Name));
 566:  
 567:             Console.ReadKey();
 568:         }
 569:     }
 570: }
 571: 变量 str 的数据类型:String
 572: 变量 i 的数据类型:Int32
 573: 变量 lst 的数据类型:List`1
 574: 变量 arr 的数据类型:String[]
 575:  
 576:  
 577: 8对象和集合初始化器
 578:  
 579: 8.1 对象的初始化
 580: using System;
 581:  
 582: namespace DemoInitializer1
 583: {
 584:     class Girlfriend
 585:     {
 586:         public string Name { get; set; }
 587:         public int Age { get; set; }
 588:     }
 589:  
 590:     class Boy
 591:     {
 592:         public string Name { get; set; }
 593:         public int Age { get; set; }
 594:         public Girlfriend Girl{ get; set; }
 595:     }
 596:  
 597:     class Program
 598:     {
 599:         static void Main(string[] args)
 600:         {
 601:             //用对象初始化器创建对象
 602:             Girlfriend gf1 = new Girlfriend { Name = "秦仙儿",  };
 603:             
 604:             //等价于
 605:             Girlfriend gf2 = new Girlfriend();
 606:             gf2.Name = "萧玉若";
 607:             gf2.Age = 21;
 608:  
 609:             //用嵌套的对象初始化器创建对象
 610:             Boy boy1 = new Boy { Name = "林晚荣", Age = 24, Girl = new Girlfriend { Name = "肖青漩", Age = 20 } };
 611:  
 612:             //等价于
 613:             Boy boy2 = new Boy();
 614:             Girlfriend gf3 = new Girlfriend();
 615:  
 616:             gf3.Name = "董巧巧";
 617:             gf3.Age = 18;
 618:             boy2.Name = "林三";
 619:             boy2.Age = 24;
 620:             boy2.Girl = gf3;
 621:  
 622:             Console.WriteLine("gf1 初始化的类型:" + gf1.GetType().Name);
 623:             Console.WriteLine("boy1 初始化的类型:" + boy1.GetType().Name);
 624:  
 625:             Console.ReadKey();
 626:         }
 627:     }
 628: }
 629:  
 630:  
 631: 8.2 集合初始化化
 632:  
 633: using System;
 634: using System.Collections.Generic;
 635:  
 636: namespace DemoInitializer2
 637: {
 638:     /// <summary>
 639:     /// 演示对象
 640:     /// </summary>
 641:     class Girlfriend
 642:     {
 643:         public string Name { get; set; }
 644:         public int Age { get; set; }
 645:     }
 646:  
 647:     /// <summary>
 648:     /// 演示对象
 649:     /// </summary>
 650:     class Boy
 651:     {
 652:         public string Name { get; set; }
 653:         public int Age { get; set; }
 654:         
 655:         /// <summary>
 656:         /// 集合属性
 657:         /// </summary>
 658:         public List<Girlfriend> Girls { get; set;}
 659:     }
 660:  
 661:  
 662:     class Program
 663:     {
 664:         static void Main(string[] args)
 665:         {
 666:             //用集合初始化器创建集合
 667:             List<string> gfs1 = new List<string> { "肖青漩", "董巧巧", "萧玉霜" };
 668:  
 669:             //等价于
 670:             List<string> gfs2 = new List<string>();
 671:             gfs2.Add("肖青漩");
 672:             gfs2.Add("董巧巧");
 673:             gfs2.Add("萧玉霜");
 674:  
 675:             //对象集合初始化器复合使用
 676:             Boy boy = new Boy { Name = "林晚荣", Age = 24, 
 677:                                     Girls = new List<Girlfriend> 
 678:                                     { 
 679:                                         new Girlfriend { Name = "肖青漩", Age = 23 }, 
 680:                                         new Girlfriend { Name = "董巧巧", Age = 18 }, 
 681:                                         new Girlfriend { Name = "萧玉霜", Age = 16 } 
 682:                                     } 
 683:                                };
 684:  
 685:  
 686:             Console.ReadKey();
 687:  
 688:         }
 689:     }
 690: }
 691:  
 692: 2.28 匿名类型
 693: 使用new 运算符和对象初始值设定项来创建。
 694:  
 695:  
 696: using System;
 697: using System.Collections.Generic;
 698: using System.Linq;
 699:  
 700: namespace DemoAnonymousType
 701: {
 702:     class Program
 703:     {
 704:         static void Main(string[] args)
 705:         {
 706:             ///创建匿名类型
 707:             var anonymous1 = new { Name = "安碧如", Title = "苗族圣姑", Age = 36 };
 708:             var anonymous2 = new { Name = "宁雨昔", Title = "圣坊仙子", Age = 37 };
 709:  
 710:             List<string> lst = new List<string> { "高丽公主", "大华军师", "霓裳公主" };
 711:  
 712:             Console.WriteLine(string.Format("anonymous1的类型:{0}", anonymous1.GetType().Name));
 713:             Console.WriteLine(string.Format("{0} {1} {2}", anonymous1.Name, anonymous1.Title, anonymous1.Age));
 714:  
 715:             Console.WriteLine(string.Format("anonymous2的类型:{0}", anonymous2.GetType().Name));
 716:             Console.WriteLine(string.Format("{0} {1} {2}", anonymous2.Name, anonymous2.Title, anonymous2.Age));
 717:  
 718:             Console.WriteLine("\n*******************************************\n");
 719:  
 720:             //LINQ select 子句中创建匿名类型
 721:             var query = from n in lst
 722:                         where n.IndexOf("公主") > -1
 723:                         select new { Name = "查询元素", Title = n };
 724:  
 725:             foreach (var item in query)
 726:             {
 727:                 Console.WriteLine(string.Format("元素的类型:{0}", item.GetType().Name));
 728:                 Console.WriteLine(string.Format("{0} {1}", item.Name, item.Title));
 729:             }
 730:  
 731:             Console.ReadKey();
 732:         }
 733:     }
 734: }
 735:  
 736: 10 扩展方法
 737: using System;
 738:  
 739: namespace DemoExtensionMethods
 740: {
 741:     public class Program
 742:     {
 743:         static void Main(string[] args)
 744:         {
 745:             string subb = "[a]http://www.baidu.com[/a]";
 746:  
 747:             Console.WriteLine(subb.UbbToHtmlLink());
 748:  
 749:             Console.WriteLine("\n");
 750:  
 751:             int i = 5;
 752:             
 753:             Console.WriteLine(string.Format("检测 i 是否为偶数:{0}",i.IsEven()));
 754:  
 755:             Console.WriteLine("\n");
 756:  
 757:             Program p = new Program();
 758:             
 759:             p.ExtensionShow();
 760:  
 761:             Console.ReadKey();
 762:         }
 763:  
 764:     }
 765: }
 766:  
 767: 12创建匿名方法
 768:  
 769: using System;
 770: using System.Collections.Generic;
 771: using System.Linq;
 772: using System.Text;
 773:  
 774: namespace DemoAnony
 775: {
 776:     class Program
 777:     {
 778:         delegate void DemoDelegate();
 779:         static void Main(string[] args)
 780:         {
 781:             DemoDelegate dele = delegate { Console.WriteLine("From the anonymousMethod"); };
 782:             dele();
 783:             Console.ReadKey();
 784:  
 785:         }
 786:     }
 787: }
 788: 13、创建Lambda表达式
 789:  
 790: using System;
 791: using System.Linq.Expressions;
 792:  
 793: namespace DemoLambda1
 794: {
 795:     class Program
 796:     {
 797:         delegate string MyDelegate(string title, string name);
 798:  
 799:         //delegate T MyDelegate2<T>(T a, T b);
 800:  
 801:         static void Main(string[] args)
 802:         {
 803:             //定义Lambda表达式
 804:             MyDelegate dele = (title, name) => string.Format("{0} {1}", title, name);
 805:  
 806:             Console.WriteLine("调用Lambda表达式\n");
 807:             //调用Lambda表达式
 808:             Console.WriteLine(dele("出云公主", "肖青漩"));
 809:             Console.WriteLine(dele("乖巧人儿", "董巧巧"));
 810:             Console.WriteLine(dele("萧家二小姐", "萧玉霜"));
 811:  
 812:             Console.WriteLine("\n*******************\n");
 813:  
 814:             string tmp = "我是Lambda语句外的变量";
 815:  
 816:             //定义Lambda语句
 817:             MyDelegate dele2 = (title, name) =>
 818:             {
 819:                 Console.WriteLine("从Lambda语句体中输出");
 820:                 Console.WriteLine(string.Format("输出外部变量tmp:{0}", tmp));
 821:                 string s;
 822:                 s = string.Format("{0} {1} 小姐", title, name);
 823:  
 824:                 return s;
 825:             };
 826:  
 827:             Console.WriteLine("调用Lambda语句\n");
 828:             //调用Lambda表达式
 829:             Console.WriteLine(dele2("霓裳公主", "秦仙儿"));
 830:  
 831:          
 832:             Console.ReadKey();
 833:         }
 834:     }
 835: }
 836:  
 837: 14 Lambda 表达式树
 838: using System;
 839: using System.Linq.Expressions;
 840:  
 841: namespace DemoLambda2
 842: {
 843:     class Program
 844:     {
 845:         static void Main(string[] args)
 846:         {
 847:             //定义Lambd表达式目录树
 848:             Expression<Func<int, bool>> tree = n => n > 168;
 849:  
 850:             //分解表达式
 851:             BinaryExpression body = (BinaryExpression)tree.Body;
 852:             ParameterExpression left = (ParameterExpression)body.Left;
 853:             ConstantExpression right = (ConstantExpression)body.Right;
 854:  
 855:             //分解结果
 856:             Console.WriteLine("分解结果: {0} {1} {2}\n",
 857:                               left.Name, body.NodeType, right.Value);
 858:  
 859:             //编译目录树
 860:             Func<int, bool> t = tree.Compile();
 861:  
 862:  
 863:             //执行目录树
 864:             Console.WriteLine(string.Format("1000 是否大于 168 :{0}", t(1000)));
 865:  
 866:  
 867:             Console.ReadKey();
 868:         }
 869:     }
 870: }
 871:  
 872: 15  C#高亮编辑及编译运行器
 873:  
 874: using System;
 875: using System.Windows.Forms;
 876:  
 877: namespace DemoCSharpEditor
 878: {
 879:     public partial class Editor : Form
 880:     {
 881:         /// <summary>
 882:         /// 控制器
 883:         /// </summary>
 884:         private EditorController ec;
 885:  
 886:         public Editor()
 887:         {
 888:             InitializeComponent();
 889:             //初始化控制器
 890:             ec = new EditorController(this.richt,this.txtlog);
 891:         }
 892:  
 893:         private void 运行ToolStripMenuItem_Click(object sender, EventArgs e)
 894:         {
 895:             ec.Compile();
 896:         }
 897:  
 898:         private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
 899:         {
 900:             this.Close();
 901:         }
 902:  
 903:         private void Editor_Load(object sender, EventArgs e)
 904:         {
 905:  
 906:         }
 907:     }
 908: }
 909: namespace DemoCSharpEditor
 910: {
 911:     partial class Editor
 912:     {
 913:         /// <summary>
 914:         /// 必需的设计器变量。
 915:         /// </summary>
 916:         private System.ComponentModel.IContainer components = null;
 917:  
 918:         /// <summary>
 919:         /// 清理所有正在使用的资源。
 920:         /// </summary>
 921:         /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
 922:         protected override void Dispose(bool disposing)
 923:         {
 924:             if (disposing && (components != null))
 925:             {
 926:                 components.Dispose();
 927:             }
 928:             base.Dispose(disposing);
 929:         }
 930:  
 931:         #region Windows 窗体设计器生成的代码
 932:  
 933:         /// <summary>
 934:         /// 设计器支持所需的方法 - 不要
 935:         /// 使用代码编辑器修改此方法的内容。
 936:         /// </summary>
 937:         private void InitializeComponent()
 938:         {
 939:             this.mainmenu = new System.Windows.Forms.MenuStrip();
 940:             this.文件FToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
 941:             this.打开OToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
 942:             this.保存SToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
 943:             this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
 944:             this.退出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
 945:             this.运行RToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
 946:             this.运行ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
 947:             this.richt = new System.Windows.Forms.RichTextBox();
 948:             this.txtlog = new System.Windows.Forms.TextBox();
 949:             this.mainmenu.SuspendLayout();
 950:             this.SuspendLayout();
 951:             // 
 952:             // mainmenu
 953:             // 
 954:             this.mainmenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
 955:             this.文件FToolStripMenuItem,
 956:             this.运行RToolStripMenuItem});
 957:             this.mainmenu.Location = new System.Drawing.Point(0, 0);
 958:             this.mainmenu.Name = "mainmenu";
 959:             this.mainmenu.Padding = new System.Windows.Forms.Padding(8, 2, 0, 2);
 960:             this.mainmenu.Size = new System.Drawing.Size(408, 28);
 961:             this.mainmenu.TabIndex = 0;
 962:             this.mainmenu.Text = "menuStrip1";
 963:             // 
 964:             // 文件FToolStripMenuItem
 965:             // 
 966:             this.文件FToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
 967:             this.打开OToolStripMenuItem,
 968:             this.保存SToolStripMenuItem,
 969:             this.toolStripMenuItem1,
 970:             this.退出ToolStripMenuItem});
 971:             this.文件FToolStripMenuItem.Name = "文件FToolStripMenuItem";
 972:             this.文件FToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
 973:             this.文件FToolStripMenuItem.Size = new System.Drawing.Size(69, 24);
 974:             this.文件FToolStripMenuItem.Text = "文件(&F)";
 975:             // 
 976:             // 打开OToolStripMenuItem
 977:             // 
 978:             this.打开OToolStripMenuItem.Name = "打开OToolStripMenuItem";
 979:             this.打开OToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
 980:             this.打开OToolStripMenuItem.Size = new System.Drawing.Size(188, 24);
 981:             this.打开OToolStripMenuItem.Text = "打开(&O)";
 982:             // 
 983:             // 保存SToolStripMenuItem
 984:             // 
 985:             this.保存SToolStripMenuItem.Name = "保存SToolStripMenuItem";
 986:             this.保存SToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
 987:             this.保存SToolStripMenuItem.Size = new System.Drawing.Size(188, 24);
 988:             this.保存SToolStripMenuItem.Text = "保存(&S)";
 989:             // 
 990:             // toolStripMenuItem1
 991:             // 
 992:             this.toolStripMenuItem1.Name = "toolStripMenuItem1";
 993:             this.toolStripMenuItem1.Size = new System.Drawing.Size(185, 6);
 994:             // 
 995:             // 退出ToolStripMenuItem
 996:             // 
 997:             this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
 998:             this.退出ToolStripMenuItem.Size = new System.Drawing.Size(188, 24);
 999:             this.退出ToolStripMenuItem.Text = "退出(&Q)";
1000:             this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);
1001:             // 
1002:             // 运行RToolStripMenuItem
1003:             // 
1004:             this.运行RToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
1005:             this.运行ToolStripMenuItem});
1006:             this.运行RToolStripMenuItem.Name = "运行RToolStripMenuItem";
1007:             this.运行RToolStripMenuItem.Size = new System.Drawing.Size(71, 24);
1008:             this.运行RToolStripMenuItem.Text = "运行(&R)";
1009:             // 
1010:             // 运行ToolStripMenuItem
1011:             // 
1012:             this.运行ToolStripMenuItem.Name = "运行ToolStripMenuItem";
1013:             this.运行ToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R)));
1014:             this.运行ToolStripMenuItem.Size = new System.Drawing.Size(164, 24);
1015:             this.运行ToolStripMenuItem.Text = "运行";
1016:             this.运行ToolStripMenuItem.Click += new System.EventHandler(this.运行ToolStripMenuItem_Click);
1017:             // 
1018:             // richt
1019:             // 
1020:             this.richt.AcceptsTab = true;
1021:             this.richt.Dock = System.Windows.Forms.DockStyle.Fill;
1022:             this.richt.Font = new System.Drawing.Font("新宋体", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
1023:             this.richt.Location = new System.Drawing.Point(0, 28);
1024:             this.richt.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
1025:             this.richt.Name = "richt";
1026:             this.richt.Size = new System.Drawing.Size(408, 183);
1027:             this.richt.TabIndex = 1;
1028:             this.richt.Text = "";
1029:             // 
1030:             // txtlog
1031:             // 
1032:             this.txtlog.Dock = System.Windows.Forms.DockStyle.Bottom;
1033:             this.txtlog.Location = new System.Drawing.Point(0, 211);
1034:             this.txtlog.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
1035:             this.txtlog.Multiline = true;
1036:             this.txtlog.Name = "txtlog";
1037:             this.txtlog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
1038:             this.txtlog.Size = new System.Drawing.Size(408, 109);
1039:             this.txtlog.TabIndex = 2;
1040:             this.txtlog.WordWrap = false;
1041:             // 
1042:             // Editor
1043:             // 
1044:             this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
1045:             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
1046:             this.ClientSize = new System.Drawing.Size(408, 320);
1047:             this.Controls.Add(this.richt);
1048:             this.Controls.Add(this.txtlog);
1049:             this.Controls.Add(this.mainmenu);
1050:             this.KeyPreview = true;
1051:             this.MainMenuStrip = this.mainmenu;
1052:             this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
1053:             this.Name = "Editor";
1054:             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
1055:             this.Text = "C Sharp 代码编辑器";
1056:             this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
1057:             this.Load += new System.EventHandler(this.Editor_Load);
1058:             this.mainmenu.ResumeLayout(false);
1059:             this.mainmenu.PerformLayout();
1060:             this.ResumeLayout(false);
1061:             this.PerformLayout();
1062:  
1063:         }
1064:  
1065:         #endregion
1066:  
1067:         private System.Windows.Forms.MenuStrip mainmenu;
1068:         private System.Windows.Forms.ToolStripMenuItem 文件FToolStripMenuItem;
1069:         private System.Windows.Forms.ToolStripMenuItem 打开OToolStripMenuItem;
1070:         private System.Windows.Forms.ToolStripMenuItem 保存SToolStripMenuItem;
1071:         private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
1072:         private System.Windows.Forms.ToolStripMenuItem 退出ToolStripMenuItem;
1073:         private System.Windows.Forms.ToolStripMenuItem 运行RToolStripMenuItem;
1074:         private System.Windows.Forms.ToolStripMenuItem 运行ToolStripMenuItem;
1075:         private System.Windows.Forms.RichTextBox richt;
1076:         private System.Windows.Forms.TextBox txtlog;
1077:     }
1078: }
1079:  
1080: using System;
1081: using System.Collections.Generic;
1082: using System.Linq;
1083: using System.Windows.Forms;
1084: using System.IO;
1085: using System.Drawing;
1086: using System.CodeDom.Compiler;
1087: using Microsoft.CSharp;
1088: using System.Reflection;
1089:  
1090: namespace DemoCSharpEditor
1091: {
1092:     /// <summary>
1093:     /// 控制器
1094:     /// </summary>
1095:     public class EditorController
1096:     {
1097:         /// <summary>
1098:         /// 高亮字颜色
1099:         /// </summary>
1100:         public Color LightColor { get; set; }
1101:  
1102:         /// <summary>
1103:         /// 文本色
1104:         /// </summary>
1105:         public Color TextColor { get; set; }
1106:  
1107:         /// <summary>
1108:         /// RichTextBox 控件引用
1109:         /// </summary>
1110:         private RichTextBox rich;
1111:  
1112:         private TextBox loginfo;
1113:  
1114:         /// <summary>
1115:         /// 关键字列表
1116:         /// </summary>
1117:         private List<string> keywords = new List<string>();
1118:  
1119:         public EditorController(RichTextBox r, TextBox l)
1120:         {
1121:             if (r == null || l == null)
1122:                 throw new Exception("控制器,初始化失败。");
1123:  
1124:             this.loginfo = l;
1125:             this.rich = r;
1126:             this.rich.KeyUp += new KeyEventHandler(rich_KeyUp);
1127:             this.LoadKeyWord();
1128:  
1129:             this.LightColor = Color.Blue;
1130:             this.TextColor = this.rich.ForeColor;
1131:         }
1132:  
1133:         void rich_KeyUp(object sender, KeyEventArgs e)
1134:         {
1135:             if (e.KeyValue < 229)
1136:                 this.LightCurrentKeyWord();
1137:         }
1138:  
1139:         /// <summary>
1140:         /// 从文本文件装载关键字列表
1141:         /// </summary>
1142:         private void LoadKeyWord()
1143:         {
1144:             string sf = "cs.txt";
1145:  
1146:             if (File.Exists(sf))
1147:             {
1148:                 keywords.Clear();
1149:                 using (StreamReader sr = new StreamReader(sf))
1150:                 {
1151:                     string sl = sr.ReadLine();
1152:                     do
1153:                     {
1154:                         if (sl != null)
1155:                             keywords.Add(sl);
1156:  
1157:                         sl = sr.ReadLine();
1158:                     } while (sl != null);
1159:                 }
1160:             }
1161:         }
1162:  
1163:         /// <summary>
1164:         /// 高亮关键字
1165:         /// </summary>
1166:         private void LightCurrentKeyWord()
1167:         {
1168:             CurrentWord last = this.rich.Text.CursorWord(this.rich.SelectionStart);
1169:  
1170:             if (last != null)
1171:             {
1172:                 var query = from w in this.keywords
1173:                             where w == last.Word
1174:                             select w;
1175:  
1176:                 int oldindex = this.rich.SelectionStart;
1177:                 int oldleng = this.rich.SelectionLength;
1178:                 this.rich.SelectionStart = last.StartIndex;
1179:                 this.rich.SelectionLength = last.Length;
1180:  
1181:                 if (query.Count<string>() > 0)
1182:                 {
1183:                     this.rich.SelectionColor = this.LightColor;
1184:                 }
1185:                 else
1186:                 {
1187:                     this.rich.SelectionColor = this.TextColor;
1188:                 }
1189:  
1190:                 this.rich.SelectionLength = oldleng;
1191:                 this.rich.SelectionStart = oldindex;
1192:                 this.rich.SelectionColor = this.TextColor;
1193:             }
1194:         }
1195:  
1196:         /// <summary>
1197:         /// 格式化代码
1198:         /// </summary>
1199:         private string MakeCode()
1200:         {
1201:             string code = @" 
1202:                     using System;
1203:                     using System.Collections.Generic;
1204:                     using System.ComponentModel;
1205:                     using System.Data;
1206:                     using System.Drawing;
1207:                     using System.Text;
1208:                     using System.Windows.Forms;
1209:                     namespace DemoTest
1210:                     {
1211:                         public class Test 
1212:                         {
1213:                             public void TestMethod() 
1214:                             {"
1215:                                 + this.rich.Text + @"
1216:                             }
1217:                         }
1218:                     }";
1219:             return code;
1220:         }
1221:  
1222:         /// <summary>
1223:         /// 编译并运行代码
1224:         /// </summary>
1225:         public void Compile()
1226:         {
1227:             this.loginfo.Text = "信息:准备编译。\n";
1228:             using (CSharpCodeProvider provider = new CSharpCodeProvider())
1229:             {
1230:                 string[] refs = { "System.dll", "System.Data.dll", "System.Deployment.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Xml.dll" };
1231:  
1232:                 CompilerParameters opt = new CompilerParameters();
1233:                 opt.ReferencedAssemblies.AddRange(refs);
1234:  
1235:                 CompilerResults res = provider.CompileAssemblyFromSource(opt, this.MakeCode());
1236:  
1237:                 if (res.Errors.Count > 0)
1238:                 {
1239:                     foreach (CompilerError e in res.Errors)
1240:                         this.loginfo.AppendText(string.Format("编译错误:{0}\n", e.ErrorText));
1241:                     return;
1242:                 }
1243:  
1244:                 this.loginfo.AppendText("信息:编译成功,准备运行。\n");
1245:                 try
1246:                 {
1247:                     Assembly assembly = res.CompiledAssembly;
1248:                     Type type = assembly.GetType("DemoTest.Test");
1249:                     object obj = Activator.CreateInstance(type);
1250:                     this.loginfo.AppendText("信息:运行。\n");
1251:                     type.GetMethod("TestMethod").Invoke(obj, null);
1252:                 }
1253:                 catch (Exception e)
1254:                 {
1255:                     this.loginfo.AppendText(string.Format("运行错误:{0} \n  {1} \n", e.Message, e.StackTrace));
1256:                 }
1257:  
1258:                 this.loginfo.AppendText("完毕。\n");
1259:             }
1260:         }
1261:  
1262:  
1263:     }
1264: }
1265:  
1266: using System;
1267: using System.Linq;
1268:  
1269: namespace DemoCSharpEditor
1270: {
1271:     /// <summary>
1272:     /// String 扩展
1273:     /// </summary>
1274:     public static class EditorExtension
1275:     {
1276:         /// <summary>
1277:         /// 单词分隔字符数组
1278:         /// </summary>
1279:         public static char[] SplitChar = { ' ', ',', '.', ';', '\n', '{', '}', '\r', Convert.ToChar(9),'(',')','[',']' };
1280:  
1281:         /// <summary>
1282:         /// 检测字符是否分割字符
1283:         /// </summary>
1284:         public static bool IsSplit(this Char chr)
1285:         {
1286:  
1287:             var query = SplitChar.Where(c => c == chr);
1288:  
1289:             if (query.Count<char>() > 0)
1290:                 return true;
1291:             else
1292:                 return false;
1293:         }
1294:  
1295:  
1296:         /// <summary>
1297:         /// 检测字符串最后一个字符是否是分割字符
1298:         /// </summary>
1299:         public static bool LastCharIsSplit(this string str, int cursorinde)
1300:         {
1301:             if (cursorinde < 1)
1302:                 return false;
1303:  
1304:             var sec = from c in SplitChar
1305:                       where c == str[cursorinde - 1]
1306:                       select c;
1307:  
1308:             if (sec.Count<char>() > 0)
1309:                 return true;
1310:             else
1311:                 return false;
1312:         }
1313:  
1314:         /// <summary>
1315:         /// 光标所在的单词
1316:         /// </summary>
1317:         public static CurrentWord CursorWord(this string str, int cursorindex)
1318:         {
1319:             if (string.IsNullOrEmpty(str))
1320:                 return null;
1321:  
1322:             if (cursorindex < 2)
1323:                 return null;
1324:  
1325:             int i = str.LastIndexOfAny(SplitChar, cursorindex - 2);
1326:             int ed = cursorindex - 2;
1327:  
1328:             if (ed < 1)
1329:                 ed = str.Length;
1330:  
1331:             if (i < 0)
1332:                 i = 0;
1333:             else
1334:                 i = i + 1;
1335:  
1336:             if (ed < str.Length)
1337:             {
1338:                 //光标不在字符串尾部,向后搜索
1339:                 ed = str.IndexOfAny(SplitChar, ed);
1340:             }
1341:  
1342:             if (ed < 0)
1343:                 return null;
1344:  
1345:             char lastc = str[ed - 1];
1346:             if (lastc.IsSplit())
1347:                 ed = ed - 1;
1348:  
1349:             ed = ed - i;
1350:  
1351:             if (ed < 1)
1352:                 return null;
1353:  
1354:             return new CurrentWord
1355:             {
1356:                 StartIndex = i,
1357:                 Length = ed,
1358:                 Word = str.Substring(i, ed)
1359:             };
1360:         }
1361:     }
1362: }
1363: using System;
1364: using System.Collections.Generic;
1365: using System.Linq;
1366: using System.Windows.Forms;
1367:  
1368: namespace DemoCSharpEditor
1369: {
1370:     static class Program
1371:     {
1372:         /// <summary>
1373:         /// 应用程序的主入口点。
1374:         /// </summary>
1375:         [STAThread]
1376:         static void Main()
1377:         {
1378:             Application.EnableVisualStyles();
1379:             Application.SetCompatibleTextRenderingDefault(false);
1380:             Application.Run(new Editor());
1381:         }
1382:     }
1383: }
1384:  
1385: 3.1  LINQ
1386: using System;
1387: using System.Collections.Generic;
1388: using System.Linq;
1389: using System.Text;
1390:  
1391: namespace DemoLinq1
1392: {
1393:     class Program
1394:     {
1395:         static void Main(string[] args)
1396:         {
1397:             string[] values = { "巧巧", "李四", "林三哥", "王五" };
1398:  
1399:             var value = from v in values where v.Length > 2 select v;
1400:  
1401:             foreach (var n in value)
1402:                 Console.WriteLine(n);
1403:  
1404:             Console.ReadKey();
1405:         }
1406:     }
1407: }
1408:  
1409: 3.2  from
1410: using System.Collections.Generic;
1411:  
1412: namespace DemoLinq
1413: {
1414:     /// <summary>
1415:     /// 客户信息
1416:     /// </summary>
1417:     public class GuestInfo
1418:     {
1419:         /// <summary>
1420:         /// 姓名
1421:         /// </summary>
1422:         public string Name { set; get; }
1423:         /// <summary>
1424:         /// 年龄
1425:         /// </summary>
1426:         public int Age { set; get; }
1427:  
1428:         /// <summary>
1429:         /// 电话
1430:         /// </summary>
1431:         public string Tel { set; get; }
1432:  
1433:         /// <summary>
1434:         /// 电话表
1435:         /// </summary>
1436:         public List<string> TelTable { set; get; }
1437:  
1438:     }
1439: }
1440:  
1441: using System;
1442: using System.Linq;
1443: using System.Collections;
1444: using DemoLinq;
1445:  
1446: namespace DemoLinq2
1447: {
1448:     class Program
1449:     {
1450:         static void Main(string[] args)
1451:         {
1452:             //初始化ArrayList
1453:             ArrayList gList = new ArrayList();
1454:             gList.Add(
1455:                 new GuestInfo { Name = "林晚荣", Age = 21, Tel = "888888**" }
1456:                 );
1457:  
1458:             gList.Add(
1459:                    new GuestInfo { Name = "宁雨昔", Age = 36, Tel = "568923**" }
1460:                    );
1461:  
1462:             gList.Add(
1463:                    new GuestInfo { Name = "洛凝", Age = 19, Tel = "985690**" }
1464:                    );
1465:  
1466:             //查询 年龄大于 19 的客户
1467:             var query = from GuestInfo guest in gList
1468:                         where guest.Age > 19
1469:                         select guest;
1470:  
1471:             //输出
1472:             foreach (GuestInfo g in query)
1473:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
1474:  
1475:             Console.ReadKey();
1476:  
1477:         }
1478:     }
1479: }
1480:  
1481: 3.2/2复合from
1482:  
1483: using System;
1484: using System.Collections.Generic;
1485: using System.Linq;
1486: using DemoLinq;
1487:  
1488: namespace DemoFrom1
1489: {
1490:     class Program
1491:     {
1492:         static void Main(string[] args)
1493:         {
1494:             //初始化集合
1495:             List<GuestInfo> gList = new List<GuestInfo>()
1496:             {
1497:                 new GuestInfo { 
1498:                     Name = "林晚荣", 
1499:                     Age = 21,  
1500:                     TelTable = new List<string>(){ 
1501:                         "026*-888888**",
1502:                         "13802588***"} 
1503:                 },
1504:                 new GuestInfo { 
1505:                     Name = "宁雨昔", 
1506:                     Age = 36,  
1507:                     TelTable = new List<string>(){ 
1508:                         "098*-568923**",
1509:                         "132679856**"} 
1510:                 },
1511:                 new GuestInfo { 
1512:                     Name = "洛凝",
1513:                     Age = 19,  
1514:                     TelTable = new List<string>(){ 
1515:                         "033*-985690**",
1516:                         "153129057**"}
1517:                 },
1518:             };
1519:  
1520:             //查找 电话号码 :132679856** 属于哪个客户
1521:             var query = from guest in gList
1522:                         from tel in guest.TelTable
1523:                         where tel.IndexOf("132679856**") > -1
1524:                         select guest;
1525:  
1526:             //输出
1527:             foreach (var g in query)
1528:             {
1529:                 Console.WriteLine(string.Format("{0} 年龄:{1}", g.Name, g.Age));
1530:                 foreach (var t in g.TelTable)
1531:                     Console.WriteLine(string.Format("       电话:{0}", t));
1532:             }
1533:  
1534:             Console.ReadKey();
1535:         }
1536:     }
1537: }
1538:  
1539: 3.2.3 多个from 子句
1540: using System;
1541: using System.Collections.Generic;
1542: using System.Linq;
1543: using DemoLinq;
1544:  
1545: namespace DemoFrom2
1546: {
1547:     class Program
1548:     {
1549:         static void Main(string[] args)
1550:         {
1551:             //初始化集合
1552:             List<GuestInfo> gList = new List<GuestInfo>()
1553:             {
1554:                 new GuestInfo 
1555:                 { 
1556:                     Name = "林晚荣", 
1557:                     Age = 21, 
1558:                     Tel = "026*-888888**" },
1559:                 new GuestInfo 
1560:                 { 
1561:                     Name = "肖青漩", 
1562:                     Age = 21, 
1563:                     Tel = "017*-876543**" 
1564:                 },
1565:                 new GuestInfo 
1566:                 { 
1567:                     Name = "董巧巧", 
1568:                     Age = 19, 
1569:                     Tel = "029*-981256**" 
1570:                 },
1571:             };
1572:  
1573:             List<GuestInfo> gList2 = new List<GuestInfo>()
1574:             {
1575:                 new GuestInfo 
1576:                 {
1577:                     Name = "萧玉霜", 
1578:                     Age = 17,
1579:                     Tel = "137052668**" 
1580:                 },
1581:                 new GuestInfo
1582:                 {
1583:                     Name = "秦仙儿", 
1584:                     Age = 20,
1585:                     Tel = "151983676**" 
1586:                 },
1587:                 new GuestInfo 
1588:                 {
1589:                     Name = "萧玉若", 
1590:                     Age = 21,
1591:                     Tel = "152987235**"
1592:                 },
1593:             };
1594:  
1595:             //guest 表查找Age大于20,
1596:             //guest2 查找Age大于17,
1597:             //结果交叉链接
1598:             var query = from guest in gList
1599:                         where guest.Age > 20
1600:                         from guest2 in gList2
1601:                         where guest2.Age > 17
1602:                         select new { guest, guest2 };
1603:  
1604:             //输出
1605:  
1606:             foreach (var g in query)
1607:                 Console.WriteLine(string.Format("{0} {1}", g.guest.Name, g.guest2.Name));
1608:  
1609:             Console.ReadKey();
1610:         }
1611:     }
1612: }
1613:  
1614: 3.3 where 子句
1615: using System;
1616: using System.Collections.Generic;
1617: using System.Linq;
1618: using DemoLinq;
1619:  
1620: namespace DemoWhere1
1621: {
1622:     class Program
1623:     {
1624:         static void Main(string[] args)
1625:         {
1626:             //初始化集合
1627:             List<GuestInfo> gList = new List<GuestInfo>()
1628:             {
1629:                 new GuestInfo 
1630:                 { 
1631:                     Name = "林晚荣", 
1632:                     Age = 21, 
1633:                     Tel = "026*-888888**" },
1634:                 new GuestInfo 
1635:                 { 
1636:                     Name = "肖青漩", 
1637:                     Age = 21, 
1638:                     Tel = "017*-876543**" 
1639:                 },
1640:                 new GuestInfo 
1641:                 { 
1642:                     Name = "董巧巧", 
1643:                     Age = 19, 
1644:                     Tel = "029*-981256**" 
1645:                 },
1646:             };
1647:  
1648:  
1649:  
1650:             ///名字是2个字或者姓"肖" 
1651:             ///并且 年龄大于等于19的客户
1652:             var query = from guest in gList
1653:                         where (guest.Name.Length == 2 ||
1654:                                 guest.Name.Substring(0, 1) == "肖") &&
1655:                                 guest.Age >= 19
1656:  
1657:                         select guest;
1658:  
1659:  
1660:             foreach (var g in query)
1661:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
1662:  
1663:             Console.ReadKey();
1664:         }
1665:     }
1666: }
1667:  
1668: 3.3.2 在where 子句中使用自定义函数
1669: using System;
1670: using System.Collections.Generic;
1671: using System.Linq;
1672: using DemoLinq;
1673:  
1674: namespace DemoWhere2
1675: {
1676:     class Program
1677:     {
1678:         static void Main(string[] args)
1679:         {
1680:             //初始化集合
1681:             List<GuestInfo> gList = new List<GuestInfo>()
1682:             {
1683:                 new GuestInfo 
1684:                 { 
1685:                     Name = "林晚荣", 
1686:                     Age = 21, 
1687:                     Tel = "026*-888888**" },
1688:                 new GuestInfo 
1689:                 { 
1690:                     Name = "肖青漩", 
1691:                     Age = 21, 
1692:                     Tel = "017*-876543**" 
1693:                 },
1694:                 new GuestInfo 
1695:                 { 
1696:                     Name = "董巧巧", 
1697:                     Age = 19, 
1698:                     Tel = "029*-981256**" 
1699:                 },
1700:             };
1701:  
1702:             //查找名字是3个字并且第一个字是“董”的信息
1703:             var query = from guest in gList
1704:                         where guest.Name.Length == 3 &&
1705:                                 Check(guest.Name)
1706:  
1707:                         select guest;
1708:  
1709:  
1710:             foreach (var g in query)
1711:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
1712:  
1713:             Console.ReadKey();
1714:  
1715:         }
1716:  
1717:         /// <summary>
1718:         /// 自定义函数 
1719:         /// 检测是否姓“董”
1720:         /// </summary>
1721:         static bool Check(string name)
1722:         {
1723:             if (name.Substring(0, 1) == "董")
1724:                 return true;
1725:  
1726:             return false;
1727:         }
1728:     }
1729: }
1730:  
1731: 3.3.3 动态谓词的筛选
1732:  
1733: using System;
1734: using System.Collections.Generic;
1735: using System.Linq;
1736: using DemoLinq;
1737:  
1738: namespace DemoWhere3
1739: {
1740:     class Program
1741:     {
1742:         static void Main(string[] args)
1743:         {
1744:             //初始化集合
1745:             List<GuestInfo> gList = new List<GuestInfo>()
1746:             {
1747:                 new GuestInfo 
1748:                 { 
1749:                     Name = "林晚荣", 
1750:                     Age = 21, 
1751:                     Tel = "026*-888888**" },
1752:                 new GuestInfo 
1753:                 { 
1754:                     Name = "肖青漩", 
1755:                     Age = 21, 
1756:                     Tel = "017*-876543**" 
1757:                 },
1758:                 new GuestInfo 
1759:                 { 
1760:                     Name = "董巧巧", 
1761:                     Age = 19, 
1762:                     Tel = "029*-981256**" 
1763:                 },
1764:             };
1765:  
1766:             //定义动态谓词数组
1767:             string[] names = { "徐长今", "萧玉若", "肖青漩", "月牙儿" };
1768:  
1769:             //查找包含在动态谓词数组中的名字
1770:             var query = from guest in gList
1771:                         where names.Contains(guest.Name)
1772:                         select guest;
1773:  
1774:             foreach (var g in query)
1775:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
1776:  
1777:             Console.ReadKey();
1778:  
1779:         }
1780:     }
1781: }
1782:  
1783: 3.4 select 子句
1784:  
1785: using System;
1786: using System.Collections.Generic;
1787: using System.Linq;
1788: using DemoLinq;
1789:  
1790: namespace DemoSelect1
1791: {
1792:     class Program
1793:     {
1794:         static void Main(string[] args)
1795:         {
1796:             //初始化集合
1797:             List<GuestInfo> gList = new List<GuestInfo>()
1798:             {
1799:                 new GuestInfo 
1800:                 { 
1801:                     Name = "宁雨昔", 
1802:                     Age = 36, 
1803:                     Tel = "098*-568923**" },
1804:                 new GuestInfo 
1805:                 { 
1806:                     Name = "肖青漩", 
1807:                     Age = 21, 
1808:                     Tel = "017*-876543**" 
1809:                 },
1810:                 new GuestInfo 
1811:                 { 
1812:                     Name = "董巧巧", 
1813:                     Age = 19, 
1814:                     Tel = "029*-981256**" 
1815:                 },
1816:             };
1817:  
1818:  
1819:             //筛选年龄小于30的客户信息并投影成MyGuestInfo类型
1820:             var query = from guest in gList
1821:                         where guest.Age < 30
1822:                         select new MyGuestInfo { Name = guest.Name, Tel = guest.Tel };
1823:  
1824:             foreach (var g in query)
1825:                 Console.WriteLine(string.Format("{0}  电话:{1} 类型:{2}", g.Name, g.Tel, g.ToString()));
1826:  
1827:             Console.ReadKey();
1828:         }
1829:     }
1830: }
1831:  
1832:  
1833: 3.5  group
1834: using System;
1835: using System.Collections.Generic;
1836: using System.Linq;
1837: using DemoLinq;
1838:  
1839: namespace DemoGurop1
1840: {
1841:     class Program
1842:     {
1843:         static void Main(string[] args)
1844:         {
1845:             //初始化集合
1846:             List<GuestInfo> gList = new List<GuestInfo>()
1847:             {
1848:                 new GuestInfo 
1849:                 { 
1850:                     Name = "萧玉霜", 
1851:                     Age = 17, 
1852:                     Tel = "053*-985690**" },
1853:                 new GuestInfo 
1854:                 { 
1855:                     Name = "萧玉若", 
1856:                     Age = 21, 
1857:                     Tel = "035*-120967**" 
1858:                 },
1859:                 new GuestInfo 
1860:                 { 
1861:                     Name = "徐长今", 
1862:                     Age = 18, 
1863:                     Tel = "039*-967512**" 
1864:                 },
1865:                 new GuestInfo 
1866:                 { 
1867:                     Name = "徐芷晴", 
1868:                     Age = 24, 
1869:                     Tel = "089*-569832**" 
1870:                 }
1871:             };
1872:  
1873:  
1874:             ////按照名字的第一个字进行分组
1875:             //var query = from guest in gList
1876:             //            group guest by guest.Name.Substring(0, 1);
1877:  
1878:             ////遍历分组数据
1879:             //foreach (IGrouping<string, GuestInfo> guestGroup in query)
1880:             //{
1881:             //    //输出当前分组的键值
1882:             //    Console.WriteLine(string.Format("分组键:{0} \n", guestGroup.Key));
1883:  
1884:             //    //遍历组内元素
1885:             //    foreach (var g in guestGroup)
1886:             //        Console.WriteLine(string.Format("{0}  电话:{1}", g.Name, g.Tel));
1887:             //    Console.WriteLine("\n**********************************\n");
1888:             //}
1889:  
1890:  
1891:  
1892:     //按照年龄是否大于20分组
1893:     var query = from guest in gList
1894:                 group guest by guest.Age > 20;
1895:  
1896:     //遍历分组数据
1897:     foreach (var guestGroup in query)
1898:     {
1899:         //输出当前分组的键值
1900:         Console.WriteLine(string.Format("年龄是否大于 20 分组键:{0} \n", guestGroup.Key));
1901:  
1902:         //遍历组内元素
1903:         foreach (var g in guestGroup)
1904:             Console.WriteLine(string.Format("{0}  电话:{1}", g.Name, g.Tel));
1905:         Console.WriteLine("\n**********************************\n");
1906:     }
1907:  
1908:             Console.ReadKey();
1909:         }
1910:     }
1911: }
1912:  
1913: 3.6  into
1914: using System;
1915: using System.Collections.Generic;
1916: using System.Linq;
1917: using DemoLinq;
1918:  
1919: namespace DemoInto
1920: {
1921:     class Program
1922:     {
1923:         static void Main(string[] args)
1924:         {
1925:             //初始化集合
1926:             List<GuestInfo> gList = new List<GuestInfo>()
1927:             {
1928:                 new GuestInfo 
1929:                 { 
1930:                     Name = "萧玉霜", 
1931:                     Age = 17, 
1932:                     Tel = "053*-985690**" },
1933:                 new GuestInfo 
1934:                 { 
1935:                     Name = "萧玉若", 
1936:                     Age = 21, 
1937:                     Tel = "035*-120967**" 
1938:                 },
1939:                 new GuestInfo 
1940:                 { 
1941:                     Name = "徐长今", 
1942:                     Age = 18, 
1943:                     Tel = "039*-967512**" 
1944:                 },
1945:                 new GuestInfo 
1946:                 { 
1947:                     Name = "徐芷晴", 
1948:                     Age = 24, 
1949:                     Tel = "089*-569832**" 
1950:                 }
1951:             };
1952:  
1953:             //按照名字的第一个字进行分组并用分组key进行排序
1954:             Console.WriteLine("into用于group子句的分组时刻");
1955:             var query = from guest in gList
1956:                         group guest by guest.Name.Substring(0, 1) into grguest
1957:                         orderby grguest.Key descending
1958:                         select grguest;
1959:  
1960:             //遍历分组数据
1961:             foreach (var guestGroup in query)
1962:             {
1963:                 //输出当前分组的键值
1964:                 Console.WriteLine(string.Format("分组键:{0} \n", guestGroup.Key));
1965:  
1966:                 //遍历组内元素
1967:                 foreach (var g in guestGroup)
1968:                     Console.WriteLine(string.Format("{0}  电话:{1}", g.Name, g.Tel));
1969:                 Console.WriteLine("\n**********************************\n");
1970:             }
1971:  
1972:             Console.WriteLine("\ninto用于select子句的投影时刻");
1973:  
1974:             //select 子句中 的 info 子句使用
1975:             var query2 = from guest in gList
1976:                          select new{NewName = guest.Name, NewAge = guest.Age} into newguest
1977:                          orderby newguest.NewAge
1978:                          select newguest;
1979:                              
1980:             //遍历分组数据
1981:             foreach (var g in query2)
1982:             {
1983:                 Console.WriteLine(string.Format("{0} 年龄:{1}", g.NewName,g.NewAge));
1984:             }
1985:  
1986:             Console.ReadKey();
1987:         }
1988:     }
1989: }
1990:  
1991: 3.7 排序子句
1992:  
1993: using System;
1994: using System.Collections.Generic;
1995: using System.Linq;
1996: using DemoLinq;
1997:  
1998: namespace DemoSort1
1999: {
2000:     class Program
2001:     {
2002:         static void Main(string[] args)
2003:         {
2004:             //初始化集合
2005:             List<GuestInfo> gList = new List<GuestInfo>()
2006:             {
2007:                 new GuestInfo 
2008:                 { 
2009:                     Name = "林晚荣", 
2010:                     Age = 21, 
2011:                     Tel = "026*-888888**" },
2012:                 new GuestInfo 
2013:                 { 
2014:                     Name = "宁雨昔", 
2015:                     Age = 36, 
2016:                     Tel = "098*-568923**" 
2017:                 },
2018:                 new GuestInfo 
2019:                 { 
2020:                     Name = "董巧巧", 
2021:                     Age = 19, 
2022:                     Tel = "029*-981256**" 
2023:                 },
2024:             };
2025:  
2026:             Console.WriteLine("按照年龄升序进行排序");
2027:             ///按照年龄升序进行排序
2028:             var query = from guest in gList
2029:                         orderby guest.Age
2030:                         select guest;
2031:  
2032:             foreach (var g in query)
2033:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
2034:  
2035:  
2036:             Console.WriteLine("\n按照年龄降序进行排序");
2037:  
2038:             ///按照年龄降序进行排序
2039:             query = from guest in gList
2040:                     orderby guest.Age descending
2041:                     select guest;
2042:  
2043:             foreach (var g in query)
2044:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
2045:  
2046:             Console.ReadKey();
2047:  
2048:         }
2049:     }
2050: }
2051:  
2052:  
2053: 3.7.2  ThenBy  和ThenByDescending 
2054:  
2055: using System;
2056: using System.Collections.Generic;
2057: using System.Linq;
2058: using DemoLinq;
2059:  
2060: namespace DemoSort2
2061: {
2062:     class Program
2063:     {
2064:         static void Main(string[] args)
2065:         {
2066:             //初始化集合
2067:             List<GuestInfo> gList = new List<GuestInfo>()
2068:             {
2069:                 new GuestInfo 
2070:                 { 
2071:                     Name = "月牙儿", 
2072:                     Age = 18, 
2073:                     Tel = "067*-781256**" 
2074:                 },
2075:                 new GuestInfo 
2076:                 { 
2077:                     Name = "徐长今", 
2078:                     Age = 18, 
2079:                     Tel = "039*-967512**" 
2080:                 },
2081:                 new GuestInfo 
2082:                 { 
2083:                     Name = "依莲", 
2084:                     Age = 18, 
2085:                     Tel = "098*-231238**" 
2086:                 },
2087:                 new GuestInfo 
2088:                 { 
2089:                     Name = "董巧巧", 
2090:                     Age = 19, 
2091:                     Tel = "029*-981256**" 
2092:                 },
2093:             };
2094:  
2095:             Console.WriteLine("按照年龄进行排序、按照名字字数进行次要排序");
2096:             ///按照年龄进行排序、按照名字字数进行次要排序
2097:             var query = from guest in gList
2098:                         orderby guest.Age,guest.Name.Length
2099:                         select guest;
2100:  
2101:             foreach (var g in query)
2102:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
2103:  
2104:             Console.WriteLine("\n按照年龄进行排序、按照名字字数进行降序次要排序");
2105:  
2106:             ///按照年龄进行排序、按照名字字数进行降序次要排序
2107:             query = from guest in gList
2108:                     orderby guest.Age, guest.Name.Length descending
2109:                     select guest;
2110:  
2111:             foreach (var g in query)
2112:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
2113:  
2114:  
2115:             Console.WriteLine("\n按照年龄进行排序、名字字数、电话排序");
2116:  
2117:             ///按照年龄进行排序、按照名字字数进行次要排序、按照电话进行第三条件排序
2118:             query = from guest in gList
2119:                     orderby guest.Age, guest.Name.Length, guest.Tel
2120:                     select guest;
2121:  
2122:             foreach (var g in query)
2123:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
2124:  
2125:           
2126:  
2127:             Console.ReadKey();
2128:         }
2129:     }
2130: }
2131:  
2132: 3.8   let 子句
2133: using System;
2134: using System.Collections.Generic;
2135: using System.Linq;
2136: using DemoLinq;
2137:  
2138: namespace DemoLet
2139: {
2140:     class Program
2141:     {
2142:         static void Main(string[] args)
2143:         {
2144:             //初始化集合
2145:             List<GuestInfo> gList = new List<GuestInfo>()
2146:             {
2147:                 new GuestInfo 
2148:                 { 
2149:                     Name = "林晚荣", 
2150:                     Age = 21, 
2151:                     Tel = "026*-888888**" },
2152:                 new GuestInfo 
2153:                 { 
2154:                     Name = "肖青漩", 
2155:                     Age = 21, 
2156:                     Tel = "017*-876543**" 
2157:                 },
2158:                 new GuestInfo 
2159:                 { 
2160:                     Name = "董巧巧", 
2161:                     Age = 19, 
2162:                     Tel = "029*-981256**" 
2163:                 },
2164:             };
2165:  
2166:  
2167:             ///姓"肖"或姓 "董"的客户
2168:             var query = from guest in gList
2169:                         let g = guest.Name.Substring(0,1)
2170:                         where g == "肖" || g == "董"
2171:                         select guest;
2172:  
2173:             foreach (var g in query)
2174:                 Console.WriteLine(string.Format("{0} 年龄:{1} 电话:{2}", g.Name, g.Age, g.Tel));
2175:  
2176:             Console.ReadKey();
2177:         }
2178:     }
2179: }
2180:  
2181: 3.9  join
2182: using System;
2183: using System.Collections.Generic;
2184: using System.Linq;
2185:  
2186: namespace DemoLinq
2187: {
2188:     class Program
2189:     {
2190:         static void Main(string[] args)
2191:         {
2192:             //初始化客户集合
2193:             List<GuestInfo> gList = new List<GuestInfo>()
2194:             {
2195:                 new GuestInfo 
2196:                 { 
2197:                     Name = "林晚荣", 
2198:                     Age = 21, 
2199:                     Tel = "026*-888888**" },
2200:                 new GuestInfo 
2201:                 { 
2202:                     Name = "肖青漩", 
2203:                     Age = 21, 
2204:                     Tel = "017*-876543**" 
2205:                 },
2206:                 new GuestInfo 
2207:                 { 
2208:                     Name = "董巧巧", 
2209:                     Age = 19, 
2210:                     Tel = "029*-981256**" 
2211:                 },
2212:                  new GuestInfo 
2213:                 { 
2214:                     Name = "徐芷晴", 
2215:                     Age = 24, 
2216:                     Tel = "089*-569832**" 
2217:                 }
2218:             };
2219:  
2220:             ///初始化客户职务集合
2221:             List<GuestTitle> titleList = new List<GuestTitle>()
2222:             {
2223:                 new GuestTitle{ Name = "林晚荣", Tilte = "金刀汉王"},
2224:                 new GuestTitle{ Name = "林晚荣", Tilte = "天下第一丁"},
2225:                 new GuestTitle{ Name = "肖青漩", Tilte = "出云公主"},
2226:                 new GuestTitle{ Name = "董巧巧", Tilte = "酒店CEO"},
2227:                 new GuestTitle{ Name = "董巧巧", Tilte = "乖巧人儿"}
2228:             };
2229:  
2230:             Console.WriteLine("内部联接");
2231:             //根据姓名进行内部联接
2232:             var query = from guest in gList
2233:                         join title in titleList on guest.Name equals title.Name
2234:                         select new { Name = guest.Name, Title = title.Tilte, Age = guest.Age };
2235:  
2236:  
2237:             foreach (var g in query)
2238:                 Console.WriteLine(string.Format("{0} {1} 年龄:{2}", g.Title, g.Name, g.Age));
2239:  
2240:  
2241:             Console.WriteLine("\n根据姓名进行分组联接");
2242:  
2243:             //根据姓名进行分组联接
2244:             var query2 = from guest in gList
2245:                          join title in titleList on guest.Name equals title.Name into tgroup
2246:                          select new { Name = guest.Name, Titles = tgroup };
2247:  
2248:             foreach (var g in query2)
2249:             {
2250:                 Console.WriteLine(g.Name);
2251:                 foreach (var g2 in g.Titles)
2252:                     Console.WriteLine(string.Format("   {0}", g2.Tilte));
2253:             }
2254:  
2255:  
2256:             Console.WriteLine("\n左外部联接");
2257:             //根据姓名进行左外部联接
2258:             var query3 = from guest in gList
2259:                          join title in titleList on guest.Name equals title.Name into tgroup
2260:                          from subtitle in tgroup.DefaultIfEmpty()
2261:                          select new { Name = guest.Name, Title = (subtitle == null ? "空缺" : subtitle.Tilte)} ;
2262:  
2263:             foreach (var g in query3)
2264:                 Console.WriteLine(string.Format("{0} {1}", g.Title, g.Name));
2265:  
2266:             Console.ReadKey();
2267:  
2268:         }
2269:     }
2270: }
2271:  
2272: 四、用于集合、文件、字符串对象的LINQ(LINQ  to  Objects)
2273:  
2274: 4.1 Take Method
2275: using System;
2276: using System.Linq;
2277: using System.Collections.Generic;
2278:  
2279: namespace DemoTake
2280: {
2281:     class Program
2282:     {
2283:         static void Main(string[] args)
2284:         {
2285:             //定义数组
2286:             string[] nemes = { "林晚荣", "洛凝", "董巧巧", "依莲", "安碧如" };
2287:  
2288:             Console.WriteLine("Take方法直接输出前3个元素");
2289:             //用Take方法直接输出前3个元素
2290:             foreach (string s in nemes.Take(3))
2291:                 Console.WriteLine(s);
2292:  
2293:             var query = from n in nemes
2294:                         where n.Length == 2
2295:                         select n;
2296:  
2297:             Console.WriteLine("\n用Take方法输出查询结果的前1个元素");
2298:  
2299:             //用Take方法输出查询结果的前1个元素
2300:             foreach (string s in query.Take(1))
2301:                 Console.WriteLine(s);
2302:  
2303:             Console.ReadKey();
2304:         }
2305:     }
2306: }
2307:  
2308: 4.2 TakeWhile
2309:  
2310: using System;
2311: using System.Linq;
2312:  
2313: namespace DemoTakeWhile1
2314: {
2315:     class Program
2316:     {
2317:         static void Main(string[] args)
2318:         {
2319:             //定义数组
2320:             string[] nemes = { "依莲", "董巧巧","洛凝", "安碧如" };
2321:  
2322:             var takenames = nemes.TakeWhile(n => n.Length == 2);
2323:  
2324:             //输出字数是2个的名字
2325:             foreach (var s in takenames)
2326:                 Console.WriteLine(s);
2327:  
2328:             Console.ReadKey();
2329:         }
2330:     }
2331: }
2332: using System;
2333: using System.Linq;
2334:  
2335: namespace DemoTakeWhile2
2336: {
2337:     class Program
2338:     {
2339:         static void Main(string[] args)
2340:         {
2341:             //定义数组
2342:             string[] nemes = { "林晚荣", "洛凝", "董巧巧","出云公主", "依莲", "安碧如" };
2343:  
2344:  
2345:             //返回元素字数小于4并且索引小于5的元素
2346:             var takenames = nemes.TakeWhile((n, i) => n.Length < 4 && i < 5);
2347:             foreach (string s in takenames)
2348:                 Console.WriteLine(s);
2349:  
2350:  
2351:             Console.ReadKey();
2352:         }
2353:     }
2354: }
2355:  
2356:  
2357: 4.4 skip
2358: using System;
2359: using System.Linq;
2360:  
2361: namespace DemoSkip
2362: {
2363:     class Program
2364:     {
2365:         static void Main(string[] args)
2366:         {
2367:             //定义数组
2368:             string[] nemes = { "林晚荣", "洛凝", "董巧巧", "依莲", "安碧如" };
2369:  
2370:             Console.WriteLine("用Skip方法跳过前3个元素后输出");
2371:             //用Skip方法跳过前3个元素后输出
2372:             foreach (string s in nemes.Skip(3))
2373:                 Console.WriteLine(s);
2374:  
2375:             var query = from n in nemes
2376:                         where n.Length == 3
2377:                         select n;
2378:  
2379:             Console.WriteLine("\n用Skip方法跳过第一个查询结果后输出");
2380:  
2381:             //用Skip方法跳过第一个查询结果后输出
2382:             foreach (string s in query.Skip(1))
2383:                 Console.WriteLine(s);
2384:  
2385:             Console.ReadKey();
2386:         }
2387:     }
2388: }
2389:  
2390: 4.5 SkipWhile
2391: using System;
2392: using System.Linq;
2393:  
2394: namespace DemoSkipWhile2
2395: {
2396:     class Program
2397:     {
2398:         static void Main(string[] args)
2399:         {
2400:             //定义数组
2401:             string[] nemes = { "林晚荣", "洛凝", "董巧巧", "出云公主", "依莲", "安碧如" };
2402:  
2403:  
2404:             //跳过元素字数小于4并且索引小于5的元素
2405:             var takenames = nemes.SkipWhile((n, i) => n.Length < 4 && i < 5);
2406:             foreach (string s in takenames)
2407:                 Console.WriteLine(s);
2408:  
2409:             Console.ReadKey();
2410:         }
2411:     }
2412: }
2413:  
2414: 4.6  Take、TakeWhile\ Skip\ SkipWhile
2415: 利用Take 和Skip实现分页
2416: using System;
2417: using System.Linq;
2418:  
2419: namespace DemoPaginate
2420: {
2421:     class Program
2422:     {
2423:         static void Main(string[] args)
2424:         {
2425:             //当前页码
2426:             int ipage = 0;
2427:             //每页记录数
2428:             int ipagesize = 2;
2429:  
2430:             //定义数组
2431:             string[] nemes = { "林晚荣", "洛凝", "董巧巧", "出云公主", "依莲", "安碧如" };
2432:  
2433:             Console.WriteLine(string.Format("输出第 {0} 页记录", ipage));
2434:             //输出第 0 页记录
2435:             var q = nemes.Skip(ipagesize * ipage).Take(ipagesize);
2436:             foreach (string s in q)
2437:                 Console.WriteLine(s);
2438:  
2439:             ipage++;
2440:             Console.WriteLine(string.Format("\n输出第 {0} 页记录", ipage));
2441:             //输出第 1 页记录
2442:             var q2 = nemes.Skip(ipagesize * ipage).Take(ipagesize);
2443:             foreach (string s in q2)
2444:                 Console.WriteLine(s);
2445:  
2446:             ipage++;
2447:             Console.WriteLine(string.Format("\n输出第 {0} 页记录", ipage));
2448:             //输出第 2 页记录
2449:             var q3 = nemes.Skip(ipagesize * ipage).Take(ipagesize);
2450:             foreach (string s in q3)
2451:                 Console.WriteLine(s);
2452:  
2453:             Console.ReadKey();
2454:  
2455:  
2456:         }
2457:     }
2458: }
2459: 4.8 Reverse 
2460:  
2461: using System;
2462: using System.Linq;
2463:  
2464: namespace DemoReverse
2465: {
2466:     class Program
2467:     {
2468:         static void Main(string[] args)
2469:         {
2470:             string str = "Reverse方法,用于反转序列中元素的顺序。";
2471:  
2472:             Console.WriteLine(str);
2473:  
2474:             Console.WriteLine("\n反转字符串\n");
2475:  
2476:             var strrev = str.ToCharArray().Reverse();
2477:             
2478:             foreach (var c in strrev)
2479:                 Console.Write(c);
2480:  
2481:             Console.ReadKey();
2482:         }
2483:     }
2484: }
2485:  
2486: 4.9 Distinct
2487: using System;
2488: using System.Linq;
2489:  
2490: namespace DemoDistinct1
2491: {
2492:     class Program
2493:     {
2494:         static void Main(string[] args)
2495:         {
2496:             ///定义一个有重复元素的数组
2497:             string[] girls = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿",
2498:                                "月牙儿", "秦仙儿", "洛凝", "萧玉霜"};
2499:  
2500:             Console.WriteLine("含有重复元素的数组");
2501:             foreach (var g in girls)
2502:                 Console.Write(string.Format("{0} ", g)); 
2503:  
2504:             var q = girls.Distinct();
2505:  
2506:             Console.WriteLine("\n\n去除重复元素的序列");
2507:             foreach (var g in q)
2508:                 Console.Write(string.Format("{0} ", g)); 
2509:  
2510:             Console.ReadKey();
2511:         }
2512:     }
2513: }
2514: 4.10  Distinct
2515:  
2516: using System.Collections.Generic;
2517:  
2518: namespace DemoDistinct2
2519: {
2520:     /// <summary>
2521:     /// 自定义相等比较器
2522:     /// </summary>
2523:     public class MyEqualityComparer<T>: IEqualityComparer<T>
2524:     {
2525:  
2526:         #region IEqualityComparer<T> 成员
2527:  
2528:         public bool Equals(T x, T y)
2529:         {
2530:             string stmp = x as string;
2531:  
2532:             if (stmp != null)
2533:             {
2534:                 if (stmp == "萧玉霜")
2535:                     return false;
2536:             }
2537:  
2538:             if (x.GetHashCode() == y.GetHashCode())
2539:                 return true;
2540:             else
2541:                 return false;
2542:         }
2543:  
2544:         public int GetHashCode(T obj)
2545:         {
2546:             return obj.GetHashCode();
2547:         }
2548:  
2549:         #endregion
2550:     }
2551: }
2552:  
2553: 4.11 Union 
2554: using System;
2555: using System.Linq;
2556:  
2557: namespace DemoDistinct2
2558: {
2559:     class Program
2560:     {
2561:         static void Main(string[] args)
2562:         {
2563:             ///定义一个有重复元素的数组
2564:             string[] girls = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿",
2565:                                "月牙儿", "萧玉霜","秦仙儿", "洛凝", "萧玉霜"};
2566:  
2567:             Console.WriteLine("含有重复元素的数组");
2568:             foreach (var g in girls)
2569:                 Console.Write(string.Format("{0} ", g));
2570:  
2571:             var q = girls.Distinct(new MyEqualityComparer<string>());
2572:  
2573:             Console.WriteLine("\n\n去除重复元素的序列");
2574:             foreach (var g in q)
2575:                 Console.Write(string.Format("{0} ", g));
2576:  
2577:             Console.ReadKey();
2578:         }
2579:     }
2580: }
2581:  
2582:  
2583: 4.12 union
2584: using System;
2585: using System.Linq;
2586: using DemoDistinct2;
2587:  
2588: namespace DemoUnion2
2589: {
2590:     class Program
2591:     {
2592:         static void Main(string[] args)
2593:         {
2594:             ///定义数组
2595:             string[] girls1 = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿" };
2596:             string[] girls2 = { "月牙儿", "秦仙儿", "洛凝", "萧玉霜" };
2597:  
2598:             var girls = girls1.Union(girls2,new MyEqualityComparer<string>());
2599:  
2600:             Console.WriteLine("合并后的序列");
2601:             foreach (var g in girls)
2602:                 Console.Write(string.Format("{0} ", g));
2603:  
2604:             Console.ReadKey();
2605:         }
2606:     }
2607: }
2608:  
2609: 4.13 Concat
2610:  
2611:  
2612: using System;
2613: using System.Linq;
2614:  
2615: namespace DemoConcat
2616: {
2617:     class Program
2618:     {
2619:         static void Main(string[] args)
2620:         {
2621:             ///定义数组
2622:             string[] girls1 = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿" };
2623:             string[] girls2 = { "月牙儿", "秦仙儿", "洛凝", "萧玉霜" };
2624:  
2625:             var girls = girls1.Concat(girls2);
2626:  
2627:             Console.WriteLine("合并后的序列");
2628:             foreach (var g in girls)
2629:                 Console.Write(string.Format("{0} ", g));
2630:  
2631:             Console.ReadKey();
2632:         }
2633:     }
2634: }
2635:  
2636: 4.14 Intersect
2637: using System;
2638: using System.Linq;
2639:  
2640: namespace DemoIntersect1
2641: {
2642:     class Program
2643:     {
2644:         static void Main(string[] args)
2645:         {
2646:             ///定义数组
2647:             string[] girls1 = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿" };
2648:             string[] girls2 = { "月牙儿", "秦仙儿", "洛凝", "萧玉霜" };
2649:  
2650:             var girls = girls1.Intersect(girls2);
2651:  
2652:             Console.WriteLine("在2个数组中都存在的元素序列");
2653:             foreach (var g in girls)
2654:                 Console.Write(string.Format("{0} ", g));
2655:  
2656:             Console.ReadKey();
2657:         }
2658:     }
2659: }
2660:  
2661: 4.15 使用自定义比较器找出两个数组汇总相同的元素
2662:  
2663: using System.Collections.Generic;
2664:  
2665: namespace DemoDistinct2
2666: {
2667:     /// <summary>
2668:     /// 自定义相等比较器
2669:     /// </summary>
2670:     public class MyEqualityComparer<T>: IEqualityComparer<T>
2671:     {
2672:  
2673:         #region IEqualityComparer<T> 成员
2674:  
2675:         public bool Equals(T x, T y)
2676:         {
2677:             string stmp = x as string;
2678:  
2679:             if (stmp != null)
2680:             {
2681:                 if (stmp == "萧玉霜")
2682:                     return false;
2683:             }
2684:  
2685:             if (x.GetHashCode() == y.GetHashCode())
2686:                 return true;
2687:             else
2688:                 return false;
2689:         }
2690:  
2691:         public int GetHashCode(T obj)
2692:         {
2693:             return obj.GetHashCode();
2694:         }
2695:  
2696:         #endregion
2697:     }
2698: }
2699: using System;
2700: using System.Linq;
2701: using DemoDistinct2;
2702:  
2703: namespace DemoIntersect2
2704: {
2705:     class Program
2706:     {
2707:         static void Main(string[] args)
2708:         {
2709:             ///定义数组
2710:             string[] girls1 = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿" };
2711:             string[] girls2 = { "月牙儿", "秦仙儿", "洛凝", "萧玉霜" };
2712:  
2713:             var girls = girls1.Intersect(girls2,new MyEqualityComparer<string>());
2714:  
2715:             Console.WriteLine("在2个数组中都存在的元素序列");
2716:             foreach (var g in girls)
2717:                 Console.Write(string.Format("{0} ", g));
2718:  
2719:             Console.ReadKey();
2720:         }
2721:     }
2722: }
2723:  
2724:  
2725: 4.16 找出两个数组中不同的元素 Except
2726: using System;
2727: using System.Linq;
2728:  
2729: namespace DemoExcept1
2730: {
2731:     class Program
2732:     {
2733:         static void Main(string[] args)
2734:         {
2735:              ///定义数组
2736:             string[] girls1 = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿" };
2737:             string[] girls2 = { "月牙儿", "秦仙儿", "洛凝", "萧玉霜" };
2738:  
2739:             var girls = girls1.Except(girls2);
2740:  
2741:             Console.WriteLine("2个数组中不同元素");
2742:             foreach (var g in girls)
2743:                 Console.Write(string.Format("{0} ", g));
2744:  
2745:             Console.ReadKey();
2746:         }
2747:     }
2748: }
2749: 4.17 使用自定义比较器找出两个数组中不同的元素Except
2750: using System;
2751: using System.Linq;
2752: using DemoDistinct2;
2753:  
2754: namespace DemoExcept2
2755: {
2756:     class Program
2757:     {
2758:         static void Main(string[] args)
2759:         {
2760:             ///定义数组
2761:             string[] girls1 = { "萧玉若", "洛凝", "萧玉霜", "秦仙儿" };
2762:             string[] girls2 = { "月牙儿", "秦仙儿", "洛凝", "萧玉霜" };
2763:  
2764:             var girls = girls1.Except(girls2, new MyEqualityComparer<string>());
2765:  
2766:             Console.WriteLine("2个数组中不同元素");
2767:             foreach (var g in girls)
2768:                 Console.Write(string.Format("{0} ", g));
2769:  
2770:             Console.ReadKey();
2771:         }
2772:     }
2773: }
2774: 4.18  Range
2775: using System;
2776: using System.Linq;
2777:  
2778: namespace DemoRange
2779: {
2780:     class Program
2781:     {
2782:         static void Main(string[] args)
2783:         {
2784:             //起始页码
2785:             int istart = 18;
2786:  
2787:             //结束页码
2788:             int iend = 26;
2789:  
2790:             var pages = Enumerable.Range(istart, iend - istart + 1);
2791:  
2792:             Console.WriteLine("输出页码");
2793:             foreach (var n in pages)
2794:                 Console.Write(string.Format("[{0}] ", n));
2795:  
2796:             Console.ReadKey();
2797:         }
2798:     }
2799: }
2800: 4.19 生成含有5个相同类型元素的序列
2801: using System;
2802: using System.Linq;
2803:  
2804: namespace DemoRepeat
2805: {
2806:     class Program
2807:     {
2808:         static void Main(string[] args)
2809:         {
2810:             ///定义一个匿名类型
2811:             var orange = new {Color="橘色",Name="桔子"};
2812:  
2813:             var oranges = Enumerable.Repeat(orange,5);
2814:  
2815:             Console.WriteLine("包含5个匿名类型的元素");
2816:             foreach (var n in oranges)
2817:                 Console.WriteLine(string.Format("{0}的{1} ", n.Color, n.Name));
2818:  
2819:             Console.ReadKey();
2820:         }
2821:     }
2822: }
2823:  
2824: 4.20 生成String 类型的空序列
2825: using System;
2826: using System.Collections.Generic;
2827: using System.Linq;
2828:  
2829: namespace DemoEmpty
2830: {
2831:     class Program
2832:     {
2833:         static void Main(string[] args)
2834:         {
2835:  
2836:             IEnumerable<string> empty = Enumerable.Empty<string>();
2837:  
2838:             Console.WriteLine(string.Format("序列元素数:{0}",empty.Count()));
2839:             
2840:             Console.ReadKey();
2841:         }
2842:     }
2843: }
2844:  
2845: 4.21 检测多种类型序列是否为空DefaultIfEmpty
2846: using System;
2847: using System.Linq;
2848:  
2849: namespace DemoDefaultIfEmpty
2850: {
2851:     class Program
2852:     {
2853:         static void Main(string[] args)
2854:         {
2855:             //定义数组
2856:             string[] nemes = { "林晚荣", "洛凝", "董巧巧", "依莲", "安碧如" };
2857:             //空的int类型序列
2858:             var intempty = Enumerable.Empty<int>();
2859:  
2860:             //没有找的元素的序列
2861:             var empty = from n in nemes
2862:                         where n == "宁雨昔"
2863:                         select n;
2864:  
2865:             Console.WriteLine("DefaultIfEmpty 返回有内容的序列");
2866:             foreach (string s in nemes.DefaultIfEmpty())
2867:                 Console.Write(string.Format("{0} ", s));
2868:  
2869:  
2870:             Console.WriteLine(string.Format("\nempty 空序列元素数:{0}", intempty.Count()));
2871:  
2872:             Console.WriteLine(string.Format("empty 空序列应用DefaultIfEmpty方法后的元素数:{0}", empty.DefaultIfEmpty().Count()));
2873:  
2874:             Console.Write(string.Format("empty 空序列应用DefaultIfEmpty方法后的元素值:"));
2875:             foreach (var s in empty.DefaultIfEmpty())
2876:                 if (s == null)
2877:                     Console.Write("null");
2878:  
2879:  
2880:             Console.WriteLine("\n\n****************************************\n");
2881:  
2882:             Console.WriteLine(string.Format("intempty 空序列元素数:{0}", intempty.Count()));
2883:  
2884:             Console.WriteLine(string.Format("intempty 空序列应用DefaultIfEmpty方法后的元素数:{0}", intempty.DefaultIfEmpty().Count()));
2885:  
2886:             Console.Write(string.Format("intempty 空序列应用DefaultIfEmpty方法后的元素值:"));
2887:             foreach (var s in intempty.DefaultIfEmpty())
2888:                 Console.Write(s);
2889:  
2890:             Console.ReadKey();
2891:         }
2892:     }
2893: }
2894:  
2895: 4.23 ArrayList 序列转换成泛型序列
2896:  
2897: using System;
2898: using System.Collections;
2899: using System.Collections.Generic;
2900: using System.Linq;
2901:  
2902: namespace DemoCast
2903: {
2904:     class Program
2905:     {
2906:         static void Main(string[] args)
2907:         {
2908:             //定义ArrayList
2909:             //由于ArrayList没有实现泛型IEnumerable<T>接口,
2910:             //所以无法用集合初始化器 
2911:             ArrayList nemes = new ArrayList();
2912:             nemes.Add( "林晚荣");
2913:             nemes.Add( "洛凝");
2914:             nemes.Add( "董巧巧");
2915:             nemes.Add( "依莲");
2916:  
2917:             IEnumerable<string> newnames = nemes.Cast<string>();
2918:  
2919:             foreach (string s in newnames)
2920:                 Console.Write(string.Format("{0} ",s));
2921:  
2922:             Console.ReadKey();
2923:         }
2924:     }
2925: }
2926:  
2927: 4.24 OfType 方法
2928: 用OfType方法转换ArrayList序列转换成泛型序列
2929: using System;
2930: using System.Collections;
2931: using System.Collections.Generic;
2932: using System.Linq;
2933:  
2934: namespace DemoOfType
2935: {
2936:     class Program
2937:     {
2938:         static void Main(string[] args)
2939:         {
2940:             //定义ArrayList
2941:             ArrayList nemes = new ArrayList();
2942:             nemes.Add("林晚荣");
2943:             nemes.Add("洛凝");
2944:             nemes.Add(100);
2945:             nemes.Add(new Stack());
2946:             nemes.Add("董巧巧");
2947:  
2948:             IEnumerable<string> newnames = nemes.OfType<string>();
2949:  
2950:             foreach (string s in newnames)
2951:                 Console.Write(string.Format("{0} ", s));
2952:  
2953:             Console.ReadKey();
2954:         }
2955:     }
2956: }
2957:  
2958: 4.25 将IQueryable 类型转换为IEnumerable类型
2959:  
2960: 4.26用于立即执行的Enumerable类方法成员
2961: using System;
2962: using System.Collections.Generic;
2963: using System.Linq;
2964:  
2965: namespace DemoToArray
2966: {
2967:     class Program
2968:     {
2969:         static void Main(string[] args)
2970:         {
2971:             ///定义List
2972:             List<string> lst = new List<string>{ "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
2973:  
2974:             var query = from t in lst
2975:                         where t.IndexOf("公主") > -1
2976:                         select t;
2977:  
2978:             string[] strarray = query.ToArray();
2979:  
2980:             Console.WriteLine(string.Format("lst 类型:{0}", lst.GetType().Name));
2981:             Console.WriteLine(string.Format("query 类型:{0}", query.GetType().Name));
2982:             Console.WriteLine(string.Format("strarray 类型:{0}", strarray.GetType().Name));
2983:             
2984:             Console.Write("\nstrarray 内容:");
2985:             foreach (string s in strarray)
2986:                 Console.Write(string.Format(" {0}", s));
2987:  
2988:             Console.ReadKey();
2989:         }
2990:     }
2991: }
2992:  
2993: 4.27 将序列转换为泛型List<T>-------ToList
2994:  
2995: using System;
2996: using System.Collections.Generic;
2997: using System.Linq;
2998:  
2999: namespace DemoToList
3000: {
3001:     class Program
3002:     {
3003:         static void Main(string[] args)
3004:         {
3005:             ///定义数组
3006:             string[] strarray = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3007:  
3008:             var query = from t in strarray
3009:                         where t.IndexOf("公主") > -1
3010:                         select t;
3011:  
3012:             List<string> lst = query.ToList();
3013:  
3014:             Console.WriteLine(string.Format("strarray 类型:{0}", strarray.GetType().Name));
3015:             Console.WriteLine(string.Format("query 类型:{0}", query.GetType().Name));
3016:             Console.WriteLine(string.Format("lst 类型:{0}", lst.GetType().Name));
3017:  
3018:             Console.Write("\nlst 内容:");
3019:             foreach (string s in lst)
3020:                 Console.Write(string.Format(" {0}", s));
3021:  
3022:             Console.ReadKey();
3023:         }
3024:     }
3025: }
3026:  
3027: 4.28 ToDictionary 
3028: using System;
3029: using System.Collections.Generic;
3030: using System.Linq;
3031: using DemoLinq;
3032:  
3033: namespace DemoToDictionary1
3034: {
3035:     class Program
3036:     {
3037:         static void Main(string[] args)
3038:         {
3039:             //初始化集合
3040:             List<GuestInfo> gList = new List<GuestInfo>()
3041:             {
3042:                 new GuestInfo 
3043:                 { 
3044:                     Name = "萧玉霜", 
3045:                     Age = 17, 
3046:                     Tel = "053*-985690**" },
3047:                 new GuestInfo 
3048:                 { 
3049:                     Name = "萧玉若", 
3050:                     Age = 21, 
3051:                     Tel = "035*-120967**" 
3052:                 },
3053:                 new GuestInfo 
3054:                 { 
3055:                     Name = "徐长今", 
3056:                     Age = 18, 
3057:                     Tel = "039*-967512**" 
3058:                 },
3059:                 new GuestInfo 
3060:                 { 
3061:                     Name = "徐芷晴", 
3062:                     Age = 24, 
3063:                     Tel = "089*-569832**" 
3064:                 }
3065:             };
3066:  
3067:  
3068:             //使用Tel属性作为Dictionary的键值
3069:             Dictionary<string, GuestInfo> dictionary = gList.ToDictionary(guest => guest.Tel);
3070:  
3071:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3072:             Console.WriteLine(string.Format("dictionary 类型:{0}", dictionary.GetType().Name));
3073:  
3074:             Console.WriteLine("\ndictionary 内容:");
3075:             foreach (string s in dictionary.Keys)
3076:                 Console.WriteLine(string.Format("键值:{0},姓名:{1}", s, dictionary[s].Name));
3077:  
3078:             Console.ReadKey();
3079:  
3080:         }
3081:     }
3082: }
3083:  
3084: using System.Collections.Generic;
3085:  
3086: namespace DemoDistinct2
3087: {
3088:     /// <summary>
3089:     /// 自定义相等比较器
3090:     /// </summary>
3091:     public class MyEqualityComparer<T>: IEqualityComparer<T>
3092:     {
3093:  
3094:         #region IEqualityComparer<T> 成员
3095:  
3096:         public bool Equals(T x, T y)
3097:         {
3098:             string stmp = x as string;
3099:  
3100:             if (stmp != null)
3101:             {
3102:                 if (stmp == "萧玉霜")
3103:                     return false;
3104:             }
3105:  
3106:             if (x.GetHashCode() == y.GetHashCode())
3107:                 return true;
3108:             else
3109:                 return false;
3110:         }
3111:  
3112:         public int GetHashCode(T obj)
3113:         {
3114:             return obj.GetHashCode();
3115:         }
3116:  
3117:         #endregion
3118:     }
3119: }
3120: using System;
3121: using System.Collections.Generic;
3122: using System.Linq;
3123: using DemoDistinct2;
3124: using DemoLinq;
3125:  
3126: namespace DemoToDictionary2
3127: {
3128:     class Program
3129:     {
3130:         static void Main(string[] args)
3131:         {
3132:             //初始化集合
3133:             List<GuestInfo> gList = new List<GuestInfo>()
3134:             {
3135:                 new GuestInfo 
3136:                 { 
3137:                     Name = "萧玉霜", 
3138:                     Age = 17, 
3139:                     Tel = "053*-985690**" },
3140:                 new GuestInfo 
3141:                 { 
3142:                     Name = "萧玉若", 
3143:                     Age = 21, 
3144:                     Tel = "035*-120967**" 
3145:                 },
3146:                 new GuestInfo 
3147:                 { 
3148:                     Name = "徐长今", 
3149:                     Age = 18, 
3150:                     Tel = "039*-967512**" 
3151:                 },
3152:                 new GuestInfo 
3153:                 { 
3154:                     Name = "徐芷晴", 
3155:                     Age = 24, 
3156:                     Tel = "089*-569832**" 
3157:                 }
3158:             };
3159:  
3160:  
3161:             //使用Name属性作为Dictionary的键值
3162:             Dictionary<string, GuestInfo> dictionary = gList.ToDictionary(guest => guest.Name,new MyEqualityComparer<string>());
3163:  
3164:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3165:             Console.WriteLine(string.Format("dictionary 类型:{0}", dictionary.GetType().Name));
3166:  
3167:             Console.WriteLine("\n检查是否有不能通过键值访问的元素");
3168:             foreach (var s in dictionary)
3169:             {
3170:                 if(!dictionary.Keys.Contains(s.Key))
3171:                     Console.WriteLine(string.Format("键值为 {0} 的内容,不能通过键值访问。", s.Key));
3172:             }
3173:  
3174:             Console.WriteLine("\n遍历dictionary全部的元素");
3175:             foreach (var s in dictionary)
3176:                 Console.WriteLine(string.Format("键值:{0},电话:{1}", s.Key, s.Value.Tel));
3177:  
3178:             Console.ReadKey();
3179:  
3180:         }
3181:     }
3182: }
3183: using System;
3184: using System.Collections.Generic;
3185: using System.Linq;
3186: using DemoLinq;
3187:  
3188: namespace DemoToDictionary3
3189: {
3190:     class Program
3191:     {
3192:         static void Main(string[] args)
3193:         {
3194:             //初始化集合
3195:             List<GuestInfo> gList = new List<GuestInfo>()
3196:             {
3197:                 new GuestInfo 
3198:                 { 
3199:                     Name = "萧玉霜", 
3200:                     Age = 17, 
3201:                     Tel = "053*-985690**" },
3202:                 new GuestInfo 
3203:                 { 
3204:                     Name = "萧玉若", 
3205:                     Age = 21, 
3206:                     Tel = "035*-120967**" 
3207:                 },
3208:                 new GuestInfo 
3209:                 { 
3210:                     Name = "徐长今", 
3211:                     Age = 18, 
3212:                     Tel = "039*-967512**" 
3213:                 },
3214:                 new GuestInfo 
3215:                 { 
3216:                     Name = "徐芷晴", 
3217:                     Age = 24, 
3218:                     Tel = "089*-569832**" 
3219:                 }
3220:             };
3221:  
3222:  
3223:             //使用Tel属性作为Dictionary的键值,Name属性作为Value值
3224:             Dictionary<string, string> dictionary = gList.ToDictionary(guest => guest.Tel,
3225:                 g=>g.Name);
3226:  
3227:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3228:             Console.WriteLine(string.Format("dictionary 类型:{0}", dictionary.GetType().Name));
3229:  
3230:             Console.WriteLine("\ndictionary 内容:");
3231:             foreach (string s in dictionary.Keys)
3232:                 Console.WriteLine(string.Format("键值:{0},姓名:{1}", s, dictionary[s]));
3233:  
3234:             Console.ReadKey();
3235:  
3236:         }
3237:     }
3238: }
3239: using System;
3240: using System.Collections.Generic;
3241: using System.Linq;
3242: using DemoDistinct2;
3243: using DemoLinq;
3244:  
3245: namespace DemoToDictionary4
3246: {
3247:     class Program
3248:     {
3249:         static void Main(string[] args)
3250:         {
3251:             //初始化集合
3252:             List<GuestInfo> gList = new List<GuestInfo>()
3253:             {
3254:                 new GuestInfo 
3255:                 { 
3256:                     Name = "萧玉霜", 
3257:                     Age = 17, 
3258:                     Tel = "053*-985690**" },
3259:                 new GuestInfo 
3260:                 { 
3261:                     Name = "萧玉若", 
3262:                     Age = 21, 
3263:                     Tel = "035*-120967**" 
3264:                 },
3265:                 new GuestInfo 
3266:                 { 
3267:                     Name = "徐长今", 
3268:                     Age = 18, 
3269:                     Tel = "039*-967512**" 
3270:                 },
3271:                 new GuestInfo 
3272:                 { 
3273:                     Name = "徐芷晴", 
3274:                     Age = 24, 
3275:                     Tel = "089*-569832**" 
3276:                 }
3277:             };
3278:  
3279:  
3280:             //使用Name属性作为Dictionary的键值,Tel属性作为Value值
3281:             Dictionary<string, string> dictionary = gList.ToDictionary(guest => guest.Name,g => g.Tel, new MyEqualityComparer<string>());
3282:  
3283:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3284:             Console.WriteLine(string.Format("dictionary 类型:{0}", dictionary.GetType().Name));
3285:  
3286:             Console.WriteLine("\n检查是否有不能通过键值访问的元素");
3287:             foreach (var s in dictionary)
3288:             {
3289:                 if (!dictionary.Keys.Contains(s.Key))
3290:                     Console.WriteLine(string.Format("键值为 {0} 的内容,不能通过键值访问。", s.Key));
3291:             }
3292:  
3293:             Console.WriteLine("\n遍历dictionary全部的元素");
3294:             foreach (var s in dictionary)
3295:                 Console.WriteLine(string.Format("键值:{0},电话:{1}", s.Key, s.Value));
3296:  
3297:             Console.ReadKey();
3298:  
3299:         }
3300:     }
3301: }
3302:  
3303: 4.32 List<GuestInfo>转换为Lookup<string,GuestInfo>类型
3304: Lookup 有些像类型转换后的分组操作
3305:  
3306: using System;
3307: using System.Collections.Generic;
3308: using System.Linq;
3309: using DemoLinq;
3310:  
3311: namespace DemoToLookup1
3312: {
3313:     class Program
3314:     {
3315:         static void Main(string[] args)
3316:         {
3317:             //初始化集合
3318:             List<GuestInfo> gList = new List<GuestInfo>()
3319:             {
3320:                 new GuestInfo 
3321:                 { 
3322:                     Name = "萧玉霜", 
3323:                     Age = 17, 
3324:                     Tel = "053*-985690**" },
3325:                 new GuestInfo 
3326:                 { 
3327:                     Name = "萧玉若", 
3328:                     Age = 21, 
3329:                     Tel = "035*-120967**" 
3330:                 },
3331:                 new GuestInfo 
3332:                 { 
3333:                     Name = "徐长今", 
3334:                     Age = 18, 
3335:                     Tel = "039*-967512**" 
3336:                 },
3337:                 new GuestInfo 
3338:                 { 
3339:                     Name = "徐芷晴", 
3340:                     Age = 24, 
3341:                     Tel = "089*-569832**" 
3342:                 }
3343:             };
3344:  
3345:  
3346:             //使用姓作为Lookup的键值
3347:             ILookup<string, GuestInfo> lookup = gList.ToLookup(guest => guest.Name.Substring(0,1));
3348:  
3349:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3350:             Console.WriteLine(string.Format("lookup 类型:{0}", lookup.GetType().Name));
3351:  
3352:             Console.WriteLine("\nlookup 内容:");
3353:             foreach (var k in lookup)
3354:             {
3355:                 Console.WriteLine(string.Format("键值:{0}", k.Key));
3356:                 foreach (var v in k)
3357:                     Console.WriteLine(string.Format("姓名:{0},年龄:{1}", v.Name,v.Age));
3358:  
3359:                 Console.WriteLine("****************************");
3360:             }
3361:             Console.ReadKey();
3362:         }
3363:     }
3364: }
3365:  
3366: using System.Collections.Generic;
3367:  
3368: namespace DemoDistinct2
3369: {
3370:     /// <summary>
3371:     /// 自定义相等比较器
3372:     /// </summary>
3373:     public class MyEqualityComparer<T>: IEqualityComparer<T>
3374:     {
3375:  
3376:         #region IEqualityComparer<T> 成员
3377:  
3378:         public bool Equals(T x, T y)
3379:         {
3380:             string stmp = x as string;
3381:  
3382:             if (stmp != null)
3383:             {
3384:                 if (stmp == "萧")
3385:                     return false;
3386:             }
3387:  
3388:             if (x.GetHashCode() == y.GetHashCode())
3389:                 return true;
3390:             else
3391:                 return false;
3392:         }
3393:  
3394:         public int GetHashCode(T obj)
3395:         {
3396:             return obj.GetHashCode();
3397:         }
3398:  
3399:         #endregion
3400:     }
3401: }
3402:  
3403: using System;
3404: using System.Collections.Generic;
3405: using System.Linq;
3406: using DemoDistinct2;
3407: using DemoLinq;
3408:  
3409: namespace DemoToLookup2
3410: {
3411:     class Program
3412:     {
3413:         static void Main(string[] args)
3414:         {
3415:             //初始化集合
3416:             List<GuestInfo> gList = new List<GuestInfo>()
3417:             {
3418:                 new GuestInfo 
3419:                 { 
3420:                     Name = "萧玉霜", 
3421:                     Age = 17, 
3422:                     Tel = "053*-985690**" },
3423:                 new GuestInfo 
3424:                 { 
3425:                     Name = "萧玉若", 
3426:                     Age = 21, 
3427:                     Tel = "035*-120967**" 
3428:                 },
3429:                 new GuestInfo 
3430:                 { 
3431:                     Name = "徐长今", 
3432:                     Age = 18, 
3433:                     Tel = "039*-967512**" 
3434:                 },
3435:                 new GuestInfo 
3436:                 { 
3437:                     Name = "徐芷晴", 
3438:                     Age = 24, 
3439:                     Tel = "089*-569832**" 
3440:                 }
3441:             };
3442:  
3443:  
3444:             //使用姓作为Lookup的键值
3445:             ILookup<string, GuestInfo> lookup = gList.ToLookup(guest => guest.Name.Substring(0, 1), new MyEqualityComparer<string>());
3446:  
3447:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3448:             Console.WriteLine(string.Format("lookup 类型:{0}", lookup.GetType().Name));
3449:  
3450:             Console.WriteLine("\nlookup 内容:");
3451:             foreach (var k in lookup)
3452:             {
3453:                 Console.WriteLine(string.Format("键值:{0}", k.Key));
3454:                 foreach (var v in k)
3455:                     Console.WriteLine(string.Format("姓名:{0},年龄:{1}", v.Name, v.Age));
3456:  
3457:                 Console.WriteLine("****************************");
3458:             }
3459:             Console.ReadKey();
3460:         }
3461:     }
3462: }
3463:  
3464:  
3465: using System;
3466: using System.Collections.Generic;
3467: using System.Linq;
3468: using DemoLinq;
3469:  
3470: namespace DemoLookup3
3471: {
3472:     class Program
3473:     {
3474:         static void Main(string[] args)
3475:         {
3476:             //初始化集合
3477:             List<GuestInfo> gList = new List<GuestInfo>()
3478:             {
3479:                 new GuestInfo 
3480:                 { 
3481:                     Name = "萧玉霜", 
3482:                     Age = 17, 
3483:                     Tel = "053*-985690**" },
3484:                 new GuestInfo 
3485:                 { 
3486:                     Name = "萧玉若", 
3487:                     Age = 21, 
3488:                     Tel = "035*-120967**" 
3489:                 },
3490:                 new GuestInfo 
3491:                 { 
3492:                     Name = "徐长今", 
3493:                     Age = 18, 
3494:                     Tel = "039*-967512**" 
3495:                 },
3496:                 new GuestInfo 
3497:                 { 
3498:                     Name = "徐芷晴", 
3499:                     Age = 24, 
3500:                     Tel = "089*-569832**" 
3501:                 }
3502:             };
3503:  
3504:  
3505:             //使用姓作为Lookup的键值Value值为Name属性
3506:             ILookup<string, string> lookup = gList.ToLookup(guest => guest.Name.Substring(0, 1),g=>g.Name);
3507:  
3508:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3509:             Console.WriteLine(string.Format("lookup 类型:{0}", lookup.GetType().Name));
3510:  
3511:             Console.WriteLine("\nlookup 内容:");
3512:             foreach (var k in lookup)
3513:             {
3514:                 Console.WriteLine(string.Format("键值:{0}", k.Key));
3515:                 foreach (var v in k)
3516:                     Console.WriteLine(string.Format("姓名:{0}", v));
3517:  
3518:                 Console.WriteLine("****************************");
3519:             }
3520:             Console.ReadKey();
3521:         }
3522:     }
3523: }
3524:  
3525:  
3526: using System.Collections.Generic;
3527:  
3528: namespace DemoDistinct2
3529: {
3530:     /// <summary>
3531:     /// 自定义相等比较器
3532:     /// </summary>
3533:     public class MyEqualityComparer<T>: IEqualityComparer<T>
3534:     {
3535:  
3536:         #region IEqualityComparer<T> 成员
3537:  
3538:         public bool Equals(T x, T y)
3539:         {
3540:             string stmp = x as string;
3541:  
3542:             if (stmp != null)
3543:             {
3544:                 if (stmp == "萧")
3545:                     return false;
3546:             }
3547:  
3548:             if (x.GetHashCode() == y.GetHashCode())
3549:                 return true;
3550:             else
3551:                 return false;
3552:         }
3553:  
3554:         public int GetHashCode(T obj)
3555:         {
3556:             return obj.GetHashCode();
3557:         }
3558:  
3559:         #endregion
3560:     }
3561: }
3562: using System;
3563: using System.Collections.Generic;
3564: using System.Linq;
3565: using DemoDistinct2;
3566: using DemoLinq;
3567:  
3568: namespace DemoToLookup4
3569: {
3570:     class Program
3571:     {
3572:         static void Main(string[] args)
3573:         {
3574:             //初始化集合
3575:             List<GuestInfo> gList = new List<GuestInfo>()
3576:             {
3577:                 new GuestInfo 
3578:                 { 
3579:                     Name = "萧玉霜", 
3580:                     Age = 17, 
3581:                     Tel = "053*-985690**" },
3582:                 new GuestInfo 
3583:                 { 
3584:                     Name = "萧玉若", 
3585:                     Age = 21, 
3586:                     Tel = "035*-120967**" 
3587:                 },
3588:                 new GuestInfo 
3589:                 { 
3590:                     Name = "徐长今", 
3591:                     Age = 18, 
3592:                     Tel = "039*-967512**" 
3593:                 },
3594:                 new GuestInfo 
3595:                 { 
3596:                     Name = "徐芷晴", 
3597:                     Age = 24, 
3598:                     Tel = "089*-569832**" 
3599:                 }
3600:             };
3601:  
3602:  
3603:             //使用姓作为Lookup的键值Name属性作为Value
3604:             ILookup<string, string> lookup = gList.ToLookup(guest => guest.Name.Substring(0, 1),g=>g.Name,new MyEqualityComparer<string>());
3605:  
3606:             Console.WriteLine(string.Format("gList 类型:{0}", gList.GetType().Name));
3607:             Console.WriteLine(string.Format("lookup 类型:{0}", lookup.GetType().Name));
3608:  
3609:             Console.WriteLine("\nlookup 内容:");
3610:             foreach (var k in lookup)
3611:             {
3612:                 Console.WriteLine(string.Format("键值:{0}", k.Key));
3613:                 foreach (var v in k)
3614:                     Console.WriteLine(string.Format("姓名:{0}", v));
3615:  
3616:                 Console.WriteLine("****************************");
3617:             }
3618:  
3619:             Console.ReadKey();
3620:         }
3621:     }
3622: }
3623:  
3624: 4.36 SequenceEqual
3625: 比较两个序列是否相等
3626: using System;
3627: using System.Linq;
3628:  
3629: namespace DemoSequenceEqual1
3630: {
3631:     class Program
3632:     {
3633:         static void Main(string[] args)
3634:         {
3635:             string[] lst1 = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3636:             string[] lst2 = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3637:             string[] lst3 = { "乖巧人儿", "出云公主", "萧家二小姐", "霓裳公主" };
3638:  
3639:             Console.WriteLine(string.Format("lst1 和 lst2 对比结果:{0}", lst1.SequenceEqual(lst2)));
3640:  
3641:             Console.WriteLine(string.Format("lst1 和 lst3 对比结果:{0}", lst1.SequenceEqual(lst3)));
3642:  
3643:             Console.ReadKey();
3644:         }
3645:     }
3646: }
3647:  
3648: 4.37 使用自定义比较器比较两个序列是否相等
3649: using System.Collections.Generic;
3650: using System.Linq;
3651:  
3652: namespace DemoSequenceEqual2
3653: {
3654:     /// <summary>
3655:     /// 自定义string数组比较器
3656:     /// </summary>
3657:     public class MyEqualityComparer2<T> : IEqualityComparer<T>
3658:     {
3659:         private string[] sec;
3660:         public MyEqualityComparer2(string[] s)
3661:         {
3662:             this.sec = s;
3663:         }
3664:  
3665:         #region IEqualityComparer<T> 成员
3666:  
3667:         public bool Equals(T x, T y)
3668:         {
3669:             string stmp = x as string;
3670:  
3671:             if (stmp != null)
3672:             {
3673:                 return sec.Contains(stmp);
3674:             }
3675:  
3676:             return false;
3677:         }
3678:  
3679:         public int GetHashCode(T obj)
3680:         {
3681:             return obj.GetHashCode();
3682:         }
3683:  
3684:         #endregion
3685:     }
3686: }
3687:  
3688: using System;
3689: using System.Linq;
3690:  
3691: namespace DemoSequenceEqual2
3692: {
3693:     class Program
3694:     {
3695:         static void Main(string[] args)
3696:         {
3697:             string[] lst1 = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3698:             string[] lst3 = { "乖巧人儿", "出云公主", "萧家二小姐", "霓裳公主" };
3699:  
3700:             Console.WriteLine(string.Format("lst1 和 lst3 对比结果:{0}", lst1.SequenceEqual(lst3,
3701:                 new MyEqualityComparer2<string>(lst3))));
3702:  
3703:             Console.ReadKey();
3704:         }
3705:     }
3706: }
3707:  
3708: 4.38 First 第一个输出
3709:  
3710: using System;
3711: using System.Linq;
3712:  
3713: namespace DemoFirst1
3714: {
3715:     class Program
3716:     {
3717:         static void Main(string[] args)
3718:         {
3719:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3720:  
3721:             var item = lst.First();
3722:  
3723:             Console.WriteLine(string.Format("数组的第一个元素:{0}", item));
3724:  
3725:             Console.ReadKey();
3726:         }
3727:     }
3728: }
3729: using System;
3730: using System.Linq;
3731:  
3732: namespace DemoFirst2
3733: {
3734:     class Program
3735:     {
3736:         static void Main(string[] args)
3737:         {
3738:             string[] lst = { "乖巧人儿", "霓裳公主", "萧家二小姐", "出云公主" };
3739:  
3740:             var item = lst.First(str=>str.IndexOf("公主")>-1);
3741:  
3742:             Console.WriteLine(string.Format("数组的第一个符合条件的元素:{0}", item));
3743:  
3744:             Console.ReadKey();
3745:         }
3746:     }
3747: }
3748:  
3749: 4.40 返回序列中第一元素,如果未找到,返回类型默认值
3750: FirstOrDefault
3751: using System;
3752: using System.Linq;
3753:  
3754: namespace DemoFirstOrDefault1
3755: {
3756:     class Program
3757:     {
3758:         static void Main(string[] args)
3759:         {
3760:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3761:             int[] lst2 = { };
3762:  
3763:             var item = lst.FirstOrDefault();
3764:             var item2 = lst2.FirstOrDefault();
3765:  
3766:             Console.WriteLine(string.Format("lst数组的第一个元素:{0}", item));
3767:             Console.WriteLine(string.Format("lst2数组的第一个元素:{0}", item2));
3768:  
3769:             Console.ReadKey();
3770:         }
3771:     }
3772: }
3773:  
3774:  
3775: using System;
3776: using System.Linq;
3777:  
3778: namespace DemoFirstOrDefault2
3779: {
3780:     class Program
3781:     {
3782:         static void Main(string[] args)
3783:         {
3784:             int[] lst = { 10,20,30,40,50,100 };
3785:  
3786:             var item = lst.FirstOrDefault(i => i==66);
3787:  
3788:             Console.WriteLine(string.Format("数组的第一个符合条件的元素:{0}", item));
3789:  
3790:             Console.ReadKey();
3791:         }
3792:     }
3793: }
3794:  
3795: 4.42 返回序列中最后一个元素 Last
3796: using System;
3797: using System.Linq;
3798:  
3799: namespace DemoLast1
3800: {
3801:     class Program
3802:     {
3803:         static void Main(string[] args)
3804:         {
3805:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3806:  
3807:             var item = lst.Last();
3808:  
3809:             Console.WriteLine(string.Format("数组的最后一个元素:{0}", item));
3810:  
3811:             Console.ReadKey();
3812:         }
3813:     }
3814: }
3815:  
3816: using System;
3817: using System.Linq;
3818:  
3819: namespace DemoLast2
3820: {
3821:     class Program
3822:     {
3823:         static void Main(string[] args)
3824:         {
3825:             string[] lst = { "乖巧人儿", "霓裳公主", "萧家二小姐", "出云公主" };
3826:  
3827:             var item = lst.Last(str => str.IndexOf("公主") > -1);
3828:  
3829:             Console.WriteLine(string.Format("数组的最后一个符合条件的元素:{0}", item));
3830:  
3831:             Console.ReadKey();
3832:         }
3833:     }
3834: }
3835:  
3836:  
3837: 4.44 LastOrDefault 方法
3838:  
3839: using System;
3840: using System.Linq;
3841:  
3842: namespace DemoLastOrDefault1
3843: {
3844:     class Program
3845:     {
3846:         static void Main(string[] args)
3847:         {
3848:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3849:             int[] lst2 = { };
3850:  
3851:             var item = lst.LastOrDefault();
3852:             var item2 = lst2.LastOrDefault();
3853:  
3854:             Console.WriteLine(string.Format("lst数组的最后一个元素:{0}", item));
3855:             Console.WriteLine(string.Format("lst2数组的最后一个元素:{0}", item2));
3856:  
3857:             Console.ReadKey();
3858:         }
3859:     }
3860: }
3861:  
3862: using System;
3863: using System.Linq;
3864:  
3865: namespace DemoLastOrDefault2
3866: {
3867:     class Program
3868:     {
3869:         static void Main(string[] args)
3870:         {
3871:             int[] lst = { 10, 20, 30, 40, 50, 100 };
3872:  
3873:             var item = lst.LastOrDefault(i => i == 66);
3874:  
3875:             Console.WriteLine(string.Format("数组的最后一个符合条件的元素:{0}", item));
3876:  
3877:             Console.ReadKey();
3878:         }
3879:     }
3880: }
3881:  
3882: 4.46 返回空序列的唯一元素Single
3883: using System;
3884: using System.Linq;
3885:  
3886: namespace DemoSingle1
3887: {
3888:     class Program
3889:     {
3890:         static void Main(string[] args)
3891:         {
3892:             string[] lst = { "乖巧人儿" };
3893:             string[] lst2 = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3894:  
3895:             var item = lst.Single();
3896:  
3897:             try
3898:             {
3899:                 var itme2 = lst2.Single();
3900:             }
3901:             catch (Exception e)
3902:             {
3903:                 Console.WriteLine(string.Format("lst2应用Single方法出错:{0}", e.Message));
3904:             }
3905:  
3906:             Console.WriteLine(string.Format("\nlst数组的唯一元素:{0}", item));
3907:  
3908:             Console.ReadKey();
3909:         }
3910:     }
3911: }
3912:  
3913:  
3914: using System;
3915: using System.Linq;
3916:  
3917: namespace DemoSingle2
3918: {
3919:     class Program
3920:     {
3921:         static void Main(string[] args)
3922:         {
3923:             string[] lst = { "乖巧人儿", "霓裳公主", "萧家二小姐", "出云公主" };
3924:  
3925:             var item = lst.Single(str => str.IndexOf("小姐") > -1);
3926:  
3927:             try
3928:             {
3929:                 var item2 = lst.Single(str => str.IndexOf("公主") > -1);
3930:             }
3931:             catch (Exception e)
3932:             {
3933:                 Console.WriteLine(string.Format("应用Single方法出错:{0}", e.Message));
3934:             }
3935:  
3936:             Console.WriteLine(string.Format("\n数组唯一符合条件的元素:{0}", item));
3937:  
3938:             Console.ReadKey();
3939:         }
3940:     }
3941: }
3942:  
3943:  
3944: 4.48 SingleOrDefault
3945:  
3946: using System;
3947: using System.Linq;
3948:  
3949: namespace DemoSingleOrDefault1
3950: {
3951:     class Program
3952:     {
3953:         static void Main(string[] args)
3954:         {
3955:  
3956:             string[] lst = { "乖巧人儿" };
3957:             int[] lst2 = { };
3958:             string[] lst3 = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
3959:  
3960:             var item = lst.SingleOrDefault();
3961:             var item2 = lst2.SingleOrDefault();
3962:  
3963:             Console.WriteLine(string.Format("lst数组的第一个元素:{0}", item));
3964:             Console.WriteLine(string.Format("lst2数组的第一个元素:{0}", item2));
3965:  
3966:             try
3967:             {
3968:                 var itme3 = lst3.Single();
3969:             }
3970:             catch (Exception e)
3971:             {
3972:                 Console.WriteLine(string.Format("\nlst3应用SingleOrDefault方法出错:{0}", e.Message));
3973:             }
3974:  
3975:  
3976:             Console.ReadKey();
3977:         }
3978:     }
3979: }
3980: using System;
3981: using System.Collections.Generic;
3982: using System.Linq;
3983: using System.Text;
3984:  
3985: namespace DemoSingleOrDefault2
3986: {
3987:     class Program
3988:     {
3989:         static void Main(string[] args)
3990:         {
3991:             int[] lst = { 10, 20, 30, 40, 50, 100, 50 };
3992:  
3993:             var item = lst.SingleOrDefault(i => i == 66);
3994:  
3995:             Console.WriteLine(string.Format("数组的唯一符合条件的元素:{0}", item));
3996:  
3997:             try
3998:             {
3999:  
4000:                 var item2 = lst.SingleOrDefault(i => i == 50);
4001:  
4002:             }
4003:             catch (Exception e)
4004:             {
4005:                 Console.WriteLine(string.Format("\n应用SingleOrDefault方法出错:{0}", e.Message));
4006:             }
4007:  
4008:  
4009:  
4010:             Console.ReadKey();
4011:         }
4012:     }
4013: }
4014:  
4015:  
4016: 4.50  ElementAt 获取指定索引处的元素
4017: using System;
4018: using System.Linq;
4019:  
4020: namespace DemoElementAt
4021: {
4022:     class Program
4023:     {
4024:         static void Main(string[] args)
4025:         {
4026:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4027:  
4028:             var item = lst.ElementAt(2);
4029:  
4030:             Console.WriteLine(string.Format("索引为2的元素:{0}", item));
4031:  
4032:             try
4033:             {
4034:                 var itme2 = lst.ElementAt(4);
4035:             }
4036:             catch (Exception e)
4037:             {
4038:                 Console.WriteLine(string.Format("\n应用ElementAt方法出错:\n{0}", e.Message));
4039:             }
4040:  
4041:             Console.ReadKey();
4042:         }
4043:     }
4044: }
4045: 4.51 ElementAtOrDefault 
4046: using System;
4047: using System.Linq;
4048:  
4049: namespace ElementAtOrDefault
4050: {
4051:     class Program
4052:     {
4053:         static void Main(string[] args)
4054:         {
4055:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4056:             int[] lst2 = { 10, 100, 1000, 1000 };
4057:  
4058:             var item = lst.ElementAtOrDefault(2);
4059:             var itme2 = lst2.ElementAtOrDefault(4);
4060:  
4061:  
4062:             Console.WriteLine(string.Format("索引为2的元素:{0}", item));
4063:             Console.WriteLine(string.Format("\n返回lst2的元素默认值:{0}", itme2));
4064:  
4065:             Console.ReadKey();
4066:         }
4067:     }
4068: }
4069:  
4070: 4.52 检测全部元素是否符合条件
4071: using System;
4072: using System.Linq;
4073:  
4074: namespace DemoAll
4075: {
4076:     class Program
4077:     {
4078:         static void Main(string[] args)
4079:         {
4080:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4081:  
4082:             bool p = lst.All(s => s.GetTypeCode() == TypeCode.String);
4083:             bool p2 = lst.All(s => s.IndexOf("公主")>-1);
4084:  
4085:             Console.WriteLine(string.Format("全部元素是否都是String类型:{0}", p));
4086:             Console.WriteLine(string.Format("\n全部元素是否都包含“公主”这个词:{0}", p2));
4087:             Console.ReadKey();
4088:         }
4089:     }
4090: }
4091:  
4092: 4.53  Any 方法
4093:  
4094: using System;
4095: using System.Linq;
4096:  
4097: namespace DemoAny1
4098: {
4099:     class Program
4100:     {
4101:         static void Main(string[] args)
4102:         {
4103:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4104:             string[] lst2 = {};
4105:  
4106:             bool p = lst.Any();
4107:             bool p2 = lst2.Any();
4108:  
4109:             Console.WriteLine(string.Format("lst是否包含元素:{0}", p));
4110:             Console.WriteLine(string.Format("\nlst2是否包含元素:{0}", p2));
4111:             Console.ReadKey();
4112:  
4113:         }
4114:     }
4115: }
4116:  
4117: using System;
4118: using System.Linq;
4119:  
4120: namespace DemoAny2
4121: {
4122:     class Program
4123:     {
4124:         static void Main(string[] args)
4125:         {
4126:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4127:  
4128:             bool p = lst.Any(s => s.IndexOf("公主") > -1);
4129:             bool p2 = lst.Any(s => s.IndexOf("仙子") > -1);
4130:  
4131:             Console.WriteLine(string.Format("是否有包含“公主”这个词的元素:{0}", p));
4132:             Console.WriteLine(string.Format("\n是否有包含“仙子”这个词的元素:{0}", p2));
4133:             Console.ReadKey();
4134:         }
4135:     }
4136: }
4137: 4.56 Contain 检测指定的元素是否存在
4138: using System;
4139: using System.Linq;
4140:  
4141: namespace DemoContains1
4142: {
4143:     class Program
4144:     {
4145:         static void Main(string[] args)
4146:         {
4147:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4148:  
4149:             bool p = lst.Contains("乖巧人儿");
4150:             bool p2 = lst.Contains("高丽公主");
4151:  
4152:             Console.WriteLine(string.Format("是否有包含“乖巧人儿”这个元素:{0}", p));
4153:             Console.WriteLine(string.Format("\n是否有包含“高丽公主”这个元素:{0}", p2));
4154:             Console.ReadKey();
4155:  
4156:         }
4157:     }
4158: }
4159: using System;
4160: using System.Linq;
4161: using DemoDistinct2;
4162:  
4163: namespace DemoContains2
4164: {
4165:     class Program
4166:     {
4167:         static void Main(string[] args)
4168:         {
4169:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主", "萧玉霜" };
4170:  
4171:             bool p = lst.Contains("萧玉霜", new MyEqualityComparer<string>());
4172:  
4173:             Console.WriteLine(string.Format("是否有包含“萧玉霜”这个元素:{0}", p));
4174:             Console.ReadKey();
4175:         }
4176:     }
4177: }
4178:  
4179:  
4180: 4.57  Count 方法获取序列元素的数量
4181: using System;
4182: using System.Linq;
4183:  
4184: namespace DemoCount1
4185: {
4186:     class Program
4187:     {
4188:         static void Main(string[] args)
4189:         {
4190:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4191:  
4192:             try
4193:             {
4194:                 
4195:                 int icount = lst.Count();
4196:  
4197:                 Console.WriteLine("序列中元素数量为: {0} ",icount);
4198:  
4199:             }
4200:             catch (OverflowException)
4201:             {
4202:                 Console.WriteLine("序列中元素数量超过Int32类型的最大值。");
4203:             }
4204:  
4205:  
4206:             Console.ReadKey();
4207:  
4208:         }
4209:     }
4210: }
4211:  
4212: 4.58 获取符合自定义条件的元素个数
4213: using System;
4214: using System.Linq;
4215:  
4216: namespace DemoCount2
4217: {
4218:     class Program
4219:     {
4220:         static void Main(string[] args)
4221:         {
4222:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4223:  
4224:             try
4225:             {
4226:  
4227:                 int icount = lst.Count(str => str.IndexOf("公主") > -1);
4228:  
4229:                 Console.WriteLine("序列中元素数量为: {0} ", icount);
4230:  
4231:             }
4232:             catch (OverflowException)
4233:             {
4234:                 Console.WriteLine("序列中元素数量超过Int32类型的最大值。");
4235:             }
4236:  
4237:  
4238:             Console.ReadKey();
4239:  
4240:         }
4241:     }
4242: }
4243:  
4244: 4.4.18 LongCount 获取一个Int64类型的元素数量
4245: using System;
4246: using System.Linq;
4247:  
4248: namespace DemoLongCount1
4249: {
4250:     class Program
4251:     {
4252:         static void Main(string[] args)
4253:         {
4254:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4255:  
4256:             long lcount = lst.LongCount();
4257:  
4258:             Console.WriteLine("序列中元素数量为: {0} ", lcount);
4259:  
4260:             Console.ReadKey();
4261:         }
4262:     }
4263: }
4264: using System;
4265: using System.Linq;
4266:  
4267: namespace DemoLongCount2
4268: {
4269:     class Program
4270:     {
4271:         static void Main(string[] args)
4272:         {
4273:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4274:  
4275:             long lcount = lst.LongCount(str => str.IndexOf("公主") > -1);
4276:  
4277:             Console.WriteLine("序列中元素数量为: {0} ", lcount);
4278:  
4279:             Console.ReadKey();
4280:         }
4281:     }
4282: }
4283:  
4284: 4.61  Aggregate 将序列元素进行累加
4285:  
4286: using System;
4287: using System.Linq;
4288:  
4289: namespace DemoAggregate3
4290: {
4291:     class Program
4292:     {
4293:         static void Main(string[] args)
4294:         {
4295:             string[] lst = { "出云公主", "乖巧人儿", "萧家二小姐", "霓裳公主" };
4296:             int[] ilst = { 10, 20, 30, 40, 50 };
4297:  
4298:             string str = lst.Aggregate("林晚荣的客户有:", (s1, s2) =>
4299:                                        string.Format("{0}、{1}", s1, s2),
4300:                                        s => s.Remove(s.IndexOf("、"), 1));
4301:  
4302:             string istr = ilst.Aggregate(50,
4303:                                         (i1, i2) => i1 + i2,
4304:                                         ii => string.Format("累加值:{0}", ii));
4305:  
4306:             Console.WriteLine(str);
4307:             Console.WriteLine(istr);
4308:             Console.ReadKey();
4309:         }
4310:     }
4311: }
4312:  
4313:  
4314: using System;
4315: using System.Linq;
4316: using System.Text.RegularExpressions;
4317:  
4318: namespace DemoCheckWord
4319: {
4320:     public partial class _Default : System.Web.UI.Page
4321:     {
4322:         protected void Page_Load(object sender, EventArgs e)
4323:         {
4324:             ///分割敏感词
4325:             string[] wordlst = this.words.Text.Split(new char[]{(char)10,(char)13}, StringSplitOptions.RemoveEmptyEntries);
4326:             ///用户提交的数据
4327:             string utext = this.UserText.Text.Replace("\n","<br>");
4328:             //敏感词掩码
4329:             string wordmask = "*";
4330:  
4331:             if (this.Page.IsPostBack)
4332:             {
4333:                 //生成正则表达式
4334:                 string pattern = wordlst.Aggregate("(?is)", 
4335:                                                     (w1, w2) => string.Format("{0}|{1}",w1, w2), 
4336:                                                     str => str.Remove(str.IndexOf("|"), 1));
4337:  
4338:                 ///找出句子包含的敏感词
4339:                 var cw = from w in wordlst
4340:                          where utext.IndexOf(w) > -1
4341:                          select w;
4342:  
4343:                 //包含的敏感词数量
4344:                 int icount = cw.Count();
4345:  
4346:                 //合并过滤掉的的敏感词
4347:                 string strwd = cw.Aggregate("<b>包含的敏感词:</b>", 
4348:                                             (w1, w2) => string.Format("{0}、{1}", w1, w2), 
4349:                                             str => str.Remove(str.IndexOf("、"), 1));
4350:  
4351:  
4352:                 //输出结果
4353:                 this.ShowText.Text = string.Format("<b>正则表达式:</b>{0}<br><b>过滤后的内容:</b><br>{1}<br>{2}<br><b>包含的敏感词数量:</b>{3}", pattern, Regex.Replace(utext, pattern, wordmask), strwd, icount);
4354:  
4355:             }
4356:         }
4357:     }
4358: }
4359:  
posted @ 2010-12-24 20:09  Space Tian  阅读(497)  评论(0编辑  收藏  举报