Skip to content

Instantly share code, notes, and snippets.

@dhei
Last active April 8, 2018 22:43
Show Gist options
  • Save dhei/04f888ded25ea16c3def659331dda395 to your computer and use it in GitHub Desktop.
Save dhei/04f888ded25ea16c3def659331dda395 to your computer and use it in GitHub Desktop.
Stackoverflow Highest Voted C# Questions

Question: Which method performs better: .Any() vs .Count() > 0? (SO link)

Answer: In general .Any() is more performant with better clarity of intention on IEnumerable<T>. If you are starting with something that has a .Length or .Count (such as ICollection, IList, List, etc) - then this will be the fastest option.

Question: Using LINQ to remove elements from a List (SO link)

Answer: .RemoveAll() from IList or .Where() will do the trick.

authorsList.RemoveAll(x => x.FirstName == "Bob");
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();

Question: LINQ's Distinct() on a particular property (SO link)

Answer: Use .GroupBy() and pick the first item.

List<Person> distinctPeople = allPeople
  .GroupBy(p => new {p.PersonId, p.FavoriteColor} )
  .Select(g => g.First())
  .ToList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment