[Reserved] List in C # and collection of First FirstOrDefault any different method

Find a qualified set of elements in List C #, in general, we will use the First method or FirstOrDefault method to return the first matching object, and call FirstOrDefault First method is to use Lambda Expressions way to write the query conditions . In fact, we recommend the use of a unified method to query FirstOrDefault List first record set qualifying, because First method in the case of information not found in any eligible objects will be thrown directly System.InvalidOperationException exception, suggesting that sequence does not contain any matching elements. The use FirstOrDefault method does not throw an exception if not found to meet the conditions set element object in the List, the default value is returned if the object type of data is returned Null, the rest of the base type returns to the default value corresponding.

For example, we have a set of List List <TestModel> Object List, TestModel class defined as follows:

 public class TestModel
    {
         public int Index { set; get; }

        public string Name { set; get; }
    }

Specific elements of a list object definition and content are as follows, containing two solid objects.

   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 using the method to find the recording Index = 12 statement: var model = list.First (t => t.Index == 12). This block of code when run directly System.InvalidOperationException exception is thrown, indicating the sequence does not contain any matching element, and then the program terminates. Whereas if FirstOrDefault method to write words, compared with the relevant statements var model = list.FirstOrDefault (t => t.Index == 12). Returns the model variable is null, only the model determines whether the subsequent code to null, the program will not run when thrown directly.

It concluded: First FirstOrDefault methods and methods to make use of FirstOrDefault find ways to achieve the implementation of the program when abnormal termination function, FirstOrDefault method does not run the program directly thrown.

Note: The text reproduced from personal bloggers station IT technology small fun house , the original link in C # First List collection methods and FirstOrDefault What is the difference _IT technology small fun house .

Guess you like

Origin www.cnblogs.com/xu-yi/p/10993585.html