在c#的list集合中查找一个符合条件的元素,一般我们会用first方法或者firstordefault方法来返回第一个符合条件的对象,first方法和firstordefault的调用都是使用lambda表达式方式来书写查询语句条件。其实建议统一使用firstordefault方法来查询list集合中符合条件的第一个记录,因为first方法在无法查到任何符合条件信息的对象的情况下,会直接抛出system.invalidoperationexception异常,提示序列不包含任何匹配元素。而使用firstordefault方法则不会抛出异常,如果在list集合中未查找到符合条件的元素对象,则返回默认值,如果是对象类型的数据则返回null,其余基础类型返回对应的默认值。

例如,我们有个list集合list<testmodel>对象list,testmodel类的定义如下:

 public class testmodel
    {
         public int index { set; get; }

        public string name { set; get; }
    }

list对象的具体定义以及内容元素如下,包含2个实体对象。

   list<testmodel> list = new list<consoleapplication1.testmodel>();
   list.add(new consoleapplication1.testmodel() { index=1,name=”text1″ });
   list.add(new consoleapplication1.testmodel() { index = 2, name = “text2” });

使用first方法来查找index=12的记录的语句为:var model = list.first(t => t.index == 12)。此代码块在运行的时候直接抛出system.invalidoperationexception异常,提示序列不包含任何匹配元素,然后程序终止执行。而如果使用firstordefault方法来书写的话,相关语句则为var model = list.firstordefault(t => t.index == 12)。返回的model变量的值为null,只需要在后续代码中判断model是否为null即可,程序在运行时候不会直接抛出异常。

得出结论:first方法和firstordefault方法尽量使用firstordefault方法来实现查找功能,firstordefault方法不会直接抛出程序运行时异常而终止程序的执行。

备注:原文转载自博主个人站it技术小趣屋,原文链接c#中list集合first和firstordefault方法有何不同_it技术小趣屋。