get only the unique items in a list in csharp

To get only the unique items in a list in C#, you can use the Distinct() method from the System.Linq namespace. Here's an example:

main.cs
using System.Linq;

// define a list with duplicate items
List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };

// get the distinct items using the Distinct method
List<int> uniqueNumbers = numbers.Distinct().ToList();

// output the unique items
foreach (int number in uniqueNumbers)
{
    Console.WriteLine(number);
}
326 chars
14 lines

This code will output:

main.cs
1
2
3
4
5
10 chars
6 lines

The Distinct() method returns an IEnumerable<T> that contains only the distinct elements of the input sequence, in this case, the numbers list. We then convert this IEnumerable<T> back to a list using the ToList() method. Finally, we loop through the uniqueNumbers list and output each item.

gistlibby LogSnag