DEV Community

Carlos Eduardo Pérez Villanueva
Carlos Eduardo Pérez Villanueva

Posted on

C# collections by Example

I've been thinking for a very long time about writing for this awesome community of developers. I think it's finally time, and I'll start by sharing some practical examples about the different things you can do with C# collections, and when you might like to use certain features.

I will mostly describe the ones I use the most at work. I work at an hospital, so I work with collections A LOT. I spend most of my day using LINQ and querying information from our database with the help of the Entity Framework. I hope to make a series of posts like this one, where I can show you examples you can refer to about different programming languages functions, libraries, and more. All with examples both theoretical and real!

Without further ado, let's get started!

Let's get the first item, shall we?

C# Collections' IEnumerable interface, gives you two methods to get the first item of a given collection. This is done through either the First(), or FirstOrDefault() methods. And I will explain both:

First()

var firstPerson = myCollectionOfPersons.First();
Console.WriteLine(firstPerson.Name);
Enter fullscreen mode Exit fullscreen mode

This is the most basic example of how to get the first item from an IEnumerable source, such as a List, for example.

Now, you might find a problem with this little guy, and it is the fact that, when there aren't any items in your collection, it will throw an exception. Which you have to write code for! (shivers...) It has happened to me more times than what I'd like to admit and it annoys me a lot. Fortunately enough, the guys at Microsoft seem to have thought the same, so we have another alternative way of calling this method. Let me introduce you to First()'s little brother: FirstOrDefault()

FirstOrDefault()

var firstPerson = myCollectionOfPersons.FirstOrDefault(p => p.Status == Status.Married);
if (firstPerson != null) {
    Console.WriteLine(firstPerson.Name);
}
Enter fullscreen mode Exit fullscreen mode

When using First() we may had to wrap the code in a try...catch block just to make sure we can handle the situation when the List is empty, which means that there isn't any first element to work with in the first place. FirstOrDefault() will return either the first element of the List, or a default value. Which can be:

  • null for any reference type (like Lists or our classes!)
  • false for boolean types
  • Zero (0) for any numeric type (integer, float, double, etc.)
  • structs are interesting. To all its properties, default values will be assigned depending on their types

I think this is all I have to say for the methods available to obtain the first value of a given collection in C#. I use it mostly when I'm 100% sure that I want to get specifically the first element of a collection. I use it a lot with LINQ's OrderBy() method. For example, I order reports by date on ascending order, then getting the first one which will, in turn, be the earliest one.

Practical example of how I use it at my job

var earliestReport = db().sp_GetAllReports().Where(r => r.CreatedBy == myUsername).OrderBy(r => r.CreationDate).First(); // this gets the first report, which is the earliest made by this user
// do business stuff with it...
Enter fullscreen mode Exit fullscreen mode

Let's check if any item in the collection meets our criteria!

Something I generally find on code written by my workmates that really grinds my gears, is them checking if a given item of a certain criteria exists by looping the collection, and then storing the knowledge of the existance of such item in a boolean value called itemExists. Oh my God, the times I had to refactor just to clean up such mess...

Thankfully, collections in C# also come with a handy little method called Any(). With Any(), we can check in a single line if an item that meets our criteria exists on a given collection. Let's see how to use it then!

Any()

if (myCollectionOfPersons.Any(p => p.Age >= 65)) {
    Console.Log("This person is an elder!");
}
Enter fullscreen mode Exit fullscreen mode

Plain and simple, we can check Collections under any criteria with this really useful method!

Practical example of how I use it at my job

if (patientsList.Any(p => p.HasInsurance)) {
   // do stuff with patients who possess insurance
}
Enter fullscreen mode Exit fullscreen mode

More to come!

Well, the post is getting a bit long and I have no other interesting tidbits to share about the subject at this moment. Let me know if this information was of any help! I'll try to write these frequently about different topics so stay tuned!

Top comments (0)