KrishnaSai Polanki
Posted on July 12, 2022
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"));
}
- 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"));
}
public List<string> Names = new List<string>() { "Jon", "Amber", "Depp Jon","Heard Amber" };
public string GetName()
{
return Names.Single(n=>n.Contains("ABC"));
}
- 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"));
}
- 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"));
}
- 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"));
}
- 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"));
}
- Returns the null(default of string type) instead of throwing error.
💖 💪 🙅 🚩
KrishnaSai Polanki
Posted on July 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.