一、firstordefault() 和 first()
class Program { static void Main(string[] args) { List<Emp> list = new List<Emp> { new Emp{ Id="001", Name="张三", Age="10", Address="河北石家庄"}, new Emp{ Id="002", Name="李四", Age="15", Address="山东济南"}, new Emp{ Id="003", Name="王五", Age="23", Address="河南郑州"} }; //firstordefault 如果找不到返回默认值 first如果找不到会发生异常 var emp = list.Where(m => m.Name == "张三").FirstOrDefault(); Console.WriteLine(emp); var emp2 = list.Where(m => m.Name == "").First(); Console.WriteLine(emp2); } } class Emp { public string Id { get; set; } public string Name { get; set; } public string Age { get; set; } public string Address { get; set; } }
二、last() lastordefault()
class Program { static void Main(string[] args) { List<Emp> list = new List<Emp> { new Emp{ Id="001", Name="张三", Age="10", Address="河北石家庄"}, new Emp{ Id="002", Name="李四", Age="15", Address="山东济南"}, new Emp{ Id="003", Name="王五", Age="23", Address="河南郑州"}, new Emp{ Id="004", Name="王五", Age="45", Address="天津武清"} }; //lastOrdefult 和last 如果找不到返回默认值 last如果找不到会发生异常 var emp = list.Where(m => m.Name == "王五").LastOrDefault(); Console.WriteLine(emp.Address); var emp2 = list.Where(m => m.Name == "").Last(); Console.WriteLine(emp2); } } class Emp { public string Id { get; set; } public string Name { get; set; } public string Age { get; set; } public string Address { get; set; } } }
三、singe() singleordefault 唯一结果查询,超过一个结果报异常
static void Main(string[] args) { List<Emp> list = new List<Emp> { new Emp{ Id="001", Name="张三", Age="10", Address="河北石家庄"}, new Emp{ Id="002", Name="李四", Age="15", Address="山东济南"}, new Emp{ Id="003", Name="王五", Age="23", Address="河南郑州"}, new Emp{ Id="004", Name="王五", Age="45", Address="天津武清"} }; // single 和singleordefault 如果序列超过一个会报异常,常用唯一结果查询 var emp = list.Where(m => m.Name == "王五").SingleOrDefault(); Console.WriteLine(emp.Address); var emp2 = list.Where(m => m.Name == "王五").Single(); Console.WriteLine(emp2); } } class Emp { public string Id { get; set; } public string Name { get; set; } public string Age { get; set; } public string Address { get; set; } }
时间: 2024-10-04 02:10:01