Date:

Share:

LINQ for beginners: pick the right methods!

Related Articles

LINQ is one of the most favorite functions of C# developers. It allows you to perform calculations and predictions across a collection of items, making your code easy to build, and even more, easy to understand.

As of C# 11, there are dozens of methods and overloads that you can choose from. Some of them look similar, but there are some differences that may not be obvious to C# beginners.

In this article, we will learn the differences between pairs of methods so that you can choose the best method that suits your needs.

First vs. FirstOrDefault

both First and FirstOrDefault allow you Get the first item of a collection that matches some requirements Passed as a parameter, usually with a lambda expression:

int[] numbers = new int[] { -2, 1, 6, 12 };

var mod3OrDefault = numbers.FirstOrDefault(n => n % 3 == 0);
var mod3 = numbers.First(n => n % 3 == 0);

Through FirstOrDefault You get the first item that matches the situation. If no items are found you will receive the Default value for this type. The default value depends on the data type:

type of information default value
int 0
wire blank
bool a lie
resist blank

To know the default value for a particular type, just run default(string).

So, back to FirstOrDefaultWe have two possible outcomes:

int[] numbers = new int[] { -2,  1, 6, 12 };
numbers.FirstOrDefault(n => n % 3 == 0); 
numbers.FirstOrDefault(n => n % 7 == 0); 

On the other hand, First throws a InvalidOperationException with the message “Sequence does not contain a matching element” If there are no items in the collection matching the filter criteria:

int[] numbers = new int[] { -2,  1, 6, 12 };
numbers.First(n => n % 3 == 0); 
numbers.First(n => n % 7 == 0); 

First vs. Single

On time First returns the first item that meets the condition, even if there are more than two or more, Single I promise it not more than one Item fits this condition.

If there are two or more items that pass the filter, a InvalidOperationException thrown away with the message “A sequence contains more than one matching element”.

int[] numbers = new int[] { -2, 1, 6, 12 };
numbers.First(n => n % 3 == 0); 
numbers.Single(n => n % 3 == 0); 

Both methods have their merits -OrDefault colleague: SingleOrDefault Returns the default value if there are no valid items.

int[] numbers = new int[] { -2, 1, 6, 12 };

numbers.SingleOrDefault(n => n % 4 == 0); 
numbers.SingleOrDefault(n => n % 7 == 0); 
numbers.SingleOrDefault(n => n % 3 == 0); 

All against a count

both Any and Count to give you indications about the presence or absence of items for which the specified predicate returns True.

int[] numbers = new int[] { -2, 1, 6, 12 };

numbers.Any(n => n % 3 == 0); 
numbers.Count(n => n % 3 == 0); 

The difference is that Any Returns a boolean, while Count Returns an integer.

where in front of Rishon

As you remember, First Returns only one item.

If you need All items that meet the specified criteria, you can use Where:

int[] numbers = new int[] { -2, 1, 6, 12 };
numbers.Where(n => n % 3 == 0); 

Sort vs. order

both Sort and Order engage in sorting the collections.

The main difference is this Sort Sorts the items in placeChanging the original collection.

However, Order and OrderBy Create a new collection of items with the same items from the original sequence but sorted.

List<int> originalNumbers = new List<int> { -7, 1, 5, -6};
originalNumbers.Sort(); 

Also, note that Sort Valid only in List<T>and not arrays or general counts.

OrderBy and Order Create a whole new collection of items.

List<int> originalNumbers = new List<int> { -7, 1, 5, -6};
var sortedNumbers = originalNumbers.OrderBy(n => n);

💡 Starting with C# 11 we can simplify OrderBy(n => n) and use Order()!

Additional readings

C# collections do not natively expose such methods. They all are extension methods.

If you want to learn what extension methods are and how you can write your own, check out this article:

🔗 How can you create extension methods in C# | Code4IT

Next, in the C# TIPS section of my blog, there are several articles you might find interesting.

One of them is about the LINQ method that you might want to know: SelectMany.

🔗 C# Tip: Select many in LINQ

This article first appeared on Code4IT 🐧

If you want to learn more about SortThe best place is the documentation:

🔗 list sorting method | Microsoft Docs

finishing

In this article we studied the differences between pairs of LINQ methods.

Each of them has a purpose, and you should use the appropriate one for each case.

❓ A question for you: talking about performance, which is more efficient: First or Single? Comment below if you know the answer! 📩

I hope you enjoyed this article! Let’s keep in touch Twitter or on LinkedIn, If you want! 🤜🤛

Happy coding!

🐧

.

Source

Popular Articles