MVC方法使用与集合:

First()与FirstOrDefault()的区别

First()当代象为NULL或没有数据时就会报错,FirstOrDefault()则不会报错而是返回NULL

异常是 IQuerable<T>.First() 方法报的,当查询的结果集为空时,调用 First() 方法将报此异常,换用 FirstOrDefault() 方法,则不报异常

 

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13 
14             List<Animal> animals=new List<Animal>();
15             Animal animal=new Animal(){Age = 45,Name = "小明",Type = "",Sex = true};
16             Animal animal1 = new Animal() { Age = 45, Name = "小F", Type = "", Sex = true };
17             Animal animal2 = new Animal() { Age = 45, Name = "小D", Type = "", Sex = true };
18             Animal animal3 = new Animal() { Age = 45, Name = "小E", Type = "", Sex = true };
19             Animal animal4 = new Animal() { Age = 45, Name = "小A", Type = "", Sex = true };
20             animals.Add(animal);
21             animals.Add(animal1);
22             animals.Add(animal2);
23             animals.Add(animal3);
24 
25             List<Person> persons = animals.Where(item => item.Type == "").Select(item => new Person()
26             {
27                 Name = item.Name,
28                 Age = item.Age,
29                 //Sex = GetSex(item.Sex),//此处注册一个方法则可执行返回结果要 也可以创建一个对象直接调用其方法: Sex = new Helper().GetSex(item.Sex)
30                 Sex = new Helper().GetSex(item.Sex)
31             }).ToList();
32 
33 
34 
35         }
36 
37 
38         public static string GetSex(bool sex)
39         {
40             if (sex)
41             {
42                 return "男人";
43             }
44             else
45             {
46                 return "女人"; 
47             }
48         }
49 
50 
51        
52     }
53 
54 
55     public class Helper
56     {
57 
58         public  string GetSex(bool sex)
59         {
60             if (sex)
61             {
62                 return "男人";
63             }
64             else
65             {
66                 return "女人";
67             }
68         }
69 
70     }
71 
72 
73     public class Person
74     {
75         public string Sex { get; set; }
76         public int Age { get; set; }
77         public string Name { get; set; }
78        
79     }
80 
81 
82 
83     public class Animal
84     {      
85        public bool Sex { get; set; }
86        public int Age { get; set; }
87        public string Name { get; set; }
88        public string Type { get; set; }
89     }
90 }
LIST集合注册方法的应用(System.Linq;)

 

posted on 2015-03-16 19:51  高达  阅读(179)  评论(0)    收藏  举报

导航