How to Use LINQ ToList in C# - Simple Guide
In C#, use
ToList() from LINQ to convert an IEnumerable or query result into a List. This method creates a new list containing all elements from the source sequence, allowing easy access and modification.Syntax
The ToList() method is called on an IEnumerable or LINQ query result to create a List of the same type.
Syntax:
var list = sourceSequence.ToList();Here:
sourceSequenceis any collection or LINQ query result.ToList()converts it into aList.listis the newListcontaining all elements.
csharp
var list = sourceSequence.ToList();Example
This example shows how to use ToList() to convert an array filtered by LINQ into a list, then print each item.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] numbers = { 1, 2, 3, 4, 5, 6 }; // Use LINQ to select even numbers and convert to List List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); // Print each even number foreach (int num in evenNumbers) { Console.WriteLine(num); } } }
Output
2
4
6
Common Pitfalls
Common mistakes when using ToList() include:
- Calling
ToList()unnecessarily on a list, causing extra copying. - Forgetting to include
using System.Linq;, which is required for LINQ methods. - Assuming
ToList()modifies the original collection (it creates a new list instead).
csharp
using System; using System.Collections.Generic; // Missing using System.Linq; causes error class Program { static void Main() { int[] numbers = { 1, 2, 3 }; // This will cause a compile error without System.Linq // List<int> list = numbers.ToList(); // Correct way: // Add 'using System.Linq;' at the top } }
Quick Reference
LINQ ToList() Quick Tips:
- Use
ToList()to get aListfrom anyIEnumerable. - Remember to add
using System.Linq;to access LINQ methods. ToList()creates a new list; original data stays unchanged.- Use it when you need to modify or index the collection.
Key Takeaways
Use ToList() to convert LINQ query results or IEnumerable to a List for easy access and modification.
Always include 'using System.Linq;' to use ToList() and other LINQ methods.
ToList() creates a new list and does not change the original collection.
Avoid unnecessary ToList() calls to prevent extra memory use.
Use ToList() when you need a concrete list instead of a lazy query.