C # Wonderful functions-2. First and Single-are you the First or only one in her mind?

Source: Internet
Author: User

First and Single in Linq are often seen in actual work. It is easy to understand from the literal meaning. One is to take the First element in the list, and the other is to get the unique element. If you want to learn more, read this article.

Translated from: C #/. NET Little Wonders: First () and Single ()-Similar Yet DifferentFirst ()-returns the First element in the sequence.

In fact, this method has four options:

  • First ()

    • Returns the first element in the sequence. If no element exists, an exception is thrown.InvalidOperationException.
  • First (Predicate <TSource>)
    • Returns the first in the sequence based on the conditions you provide. If no element exists, an exception is thrown. InvalidOperationException.
  • FirstOrDefault ()
    • Returns the first element in the sequence. If no element exists, the default element is returned.Default (TSource ).
  • FirstOrDefault (Predicate <TSource>)
    • Returns the first element in the sequence based on the conditions you provide. If no element exists, the default element is returned.Default (TSource ).

The core idea of First is to return the First element if there is more than one element in the sequence. This also means that when the first element is found, the called method immediately exits and will not traverse to find the remaining elements.

For example, define a class:

  public sealed class Employee {     public long Id { get; set; }     public string Name { get; set; }     public double Salary { get; set; } }

Give him some initialization lists: Empty, one element, multiple element

// Empty table var noEmployeeList = new List <Employee> (); // one element var oneEmployeeList = new List <Employee> {new Employee {Id = 55, name = "Sussie Queue", Salary = 60000.50 }}; // multiple elements var employees = new List <Employee> {new Employee {Id = 1, name = "Jim Smith", Salary = 12345.50}, new Employee {Id = 7, Name = "Jane Doe", Salary = 31234.50}, new Employee {Id = 9, name = "John Doe", Salary = 13923.99}, new Employee {Id = 13, Name = "Jim Smith", Salary = 30123.49 },//... etc ...};

Well, what will happen to them when we use First?

 var first = employees.First();var firstJohn = employees.First(e => e.Name.StartsWith("John"));var firstDoe = employee.First(e => e.Name.EndsWith("Doe"));

Note that an exception is thrown in the following situations:

 var empty = noEmployees.First();var noMatch = employees.First(e => e.Id == 20);

Finally, when we use the method with Default, the following situation will return a null value instead of throwing an exception:

 var empty = noEmployees.FirstOrDefault();var noMatch = employees.FirstOrDefault(e => e.Id == 20);

Single ()-one and only one

Like First, Single has four forms:

  • Single ()
    • Returns the unique element in the sequence. If no element exists, an exception is thrown.InvalidOperationException,If there are more than one, an exception is thrown.InvalidOperationException.
  • Single (Predicate <TSource>)
    • Based on your conditionsReturns the unique element in the sequence. If no element exists, an exception is thrown.InvalidOperationException,If there are more than one, an exception is thrown.InvalidOperationException.SingleOrDefault ()
  • SingleOrDefault ()
  • Returns the unique element in the sequence,If no element exists, the default element is returned.Default (TSource),If there are more than one, an exception is thrown.InvalidOperationException.
  • SingleOrDefault (Predicate <TSource>)
    • Based on your conditionsReturns the unique element in the sequence,If no element exists, the default element is returned.Default (TSource),If there are more than one, an exception is thrown.InvalidOperationException.
  • Note that the key difference is mainly here: if there is more than one element, this family of methods will always throwInvalidOperationException exception.Note that this means that even if the Single method gets a matching element, it may still scan the remaining enumeration. This reduces the Single efficiency.

    Which of the following examples return?

     var oneAndOnly = oneEmployeeList.Single();var throwsOnEmpty = noEmployeeList.Single();var throwsOnMultiple = employeeList.Single();

    From the example below, we can see the similarity between Single and First. The difference is that the sequence that satisfies the result is more than one element.

    // Obtain the unique element var oneAndOnlyMatch = oneEmployeeList whose ID = 7. single (e => e. id = 7); // throw an exception var throwsOnNoMatches = noEmployeeList. single (e => e. id = 999); // throw an exception var throwsOnMultipleMatches = employeeList. single (e => e. name. endsWith ("Doe"); // returns a null element. var defaultsOnEmpty = noEmployeeList. singleOrDefault (); // returns a null element. var defaultsOnNoMatch = noEmployeeList. singleOrDefault (e => e. id = 999 );

    Conclusion

    Both First and Single have an option to avoid throwing an exception when no element meets the requirements. When you are not sure whether the element you want to obtain exists, you can use... OrDefault (), because null can indicate "no ".

    If you do not care whether there are duplicate items or there are no repeated elements, you can use First. If you want to check whether there are duplicate elements, you can choose Single.

    Thank you for reading this article. For more. NET topics, please go:

    ASP. NET

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.