To remove duplicates from a C# list using Linq, do the following.
- Define a new list. Ours has 7 elements, with “2” and “4” repeating
- Use Distinct().ToList() to make a new list with the distinct elements
- Print out to the console
using System; using System.Collections.Generic; using System.Linq; namespace Carl.RemoveDuplicatesList { class Program { static void Main(string[] args) { // Create list with non-unique values List<string> l = new List<string>(); l.Add("1"); l.Add("2"); l.Add("2"); // duplicate l.Add("3"); l.Add("4"); l.Add("4"); // duplicate l.Add("5"); // Make new unique list List<string> uniqueList = l.Distinct().ToList(); // Write to console uniqueList.ForEach(i => Console.WriteLine($"{i}")); Console.ReadLine(); } } }
This outputs:
THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL
Thank you for the very clear example of how to obtain a unique list. But what if you have a generic collection list? I have that and I am trying to obtain a unique list based on one field in that collection.
Write a function which takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once.