The LINQ distinct()
function is used in C# to remove all the duplicate elements from a list and return the unique elements present in that particular list.
obj.Select(s => s.gpa).Distinct();
Here, obj
is the object of a class, and gpa
is the particular property we are selecting from the class.
It will take the list of a particular property from where you want to remove repetitive elements.
The distinct()
function returns a list of elements from the source after removing duplicates. If no copies are present, it will return the same list. It can store either in var or list.
Note: We are using
var
; this variable type depends on the initial value it stores.
The code below will explain how to use distinct()
.
using System;using System.Linq;using System.Collections.Generic;public class Animals{public string Name { get; set; }public int ID { get; set; }static public void Main(){var zoo = new List<Animals>();zoo.Add(new Animals() { Name = "Monkey", ID = 1 });zoo.Add(new Animals() { Name = "Lion", ID = 2 });zoo.Add(new Animals() { Name = "Monkey", ID = 3 });zoo.Add(new Animals() { Name = "Tiger", ID = 2 });zoo.Add(new Animals() { Name = "Lion", ID = 4 });var result =zoo.Select(s => s.Name).Distinct();foreach (var animal in result){Console.WriteLine(animal);}}}
Animals
.zoo
.zoo
list.Name
from the zoo
class and store it in the result.Free Resources