DEV Community

KrishnaSai Polanki
KrishnaSai Polanki

Posted on

Single, SingleOrDefault, First and FirstOrDefault in LINQ

Single

  • Returns the result only when predicate matches the collection that contains only one matching record.
    public List<string> Names = new List<string>() { "Jon", "Amber"};

    public string GetName()
    {
        return Names.Single(n=>n.Equals("Jon"));
    }
Enter fullscreen mode Exit fullscreen mode
  • Throws error if the collection contains more than one matching data or no matching data.
    public List<string> Names = new List<string>() { "Jon", "Amber", "Depp Jon","Heard Amber" };

    public string GetName()
    {
        return Names.Single(n=>n.Contains("Jon"));
    }
Enter fullscreen mode Exit fullscreen mode
    public List<string> Names = new List<string>() { "Jon", "Amber", "Depp Jon","Heard Amber" };

    public string GetName()
    {
        return Names.Single(n=>n.Contains("ABC"));
    }
Enter fullscreen mode Exit fullscreen mode
  • Loops through all the data of the collection even if it found the match in collection which has impact on performance.

SingleOrDefault

  • This is similar to the Single except returning default value when the specified condition not satisfied.
    public List<string> Names = new List<string>() { "Jon", "Amber", "Depp Jon","Heard Amber" };

    public string GetName()
    {
        return Names.SingleOrDefault(n=>n.Contains("ABC"));
    }
Enter fullscreen mode Exit fullscreen mode
  • Returns the null(default of string type) instead of throwing error.

First

  • Returns the result only when predicate matches the collection even that contains more than one matching record.
    public List<string> Names = new List<string>() { "Jon", "Amber", "Depp Jon","Heard Amber" };

    public string GetName()
    {
        return Names.First(n=>n.Contains("Jon"));
    }
Enter fullscreen mode Exit fullscreen mode
  • Throws error if the collection contains no matching data.
    public List<string> Names = new List<string>() { "Jon", "Amber", "Depp Jon","Heard Amber" };

    public string GetName()
    {
        return Names.First(n=>n.Contains("ABC"));
    }
Enter fullscreen mode Exit fullscreen mode
  • Will not loops through all the data of the collection once it found the match in collection thus making this is better than Single in terms of performance.

FirstOrDefault

  • This is similar to the First except returning default value when the specified condition not satisfied.
    public List<string> Names = new List<string>() { "Jon", "Amber", "Depp Jon","Heard Amber" };

    public string GetName()
    {
        return Names.FirstOrDefault(n=>n.Contains("ABC"));
    }
Enter fullscreen mode Exit fullscreen mode
  • Returns the null(default of string type) instead of throwing error.

Top comments (0)