How to apply LINQ's Distinct() over a particular property

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.

Syntax

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.

Parameters

It will take the list of a particular property from where you want to remove repetitive elements.

Return type

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.

Example

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);
}
}
}

Explanation

  • Lines 1–3: We use necessary directives.
  • Line 5: We create a class name Animals.
  • Lines 7–8: We create two parameters for our class.
  • Line 12: We create an object of a class name zoo.
  • Lines 13–17: We add data to our class zoo list.
  • Lines 19: We select a property Name from the zoo class and store it in the result.
  • Lines 21–23: We print the removed elements from the chosen property.

Copyright ©2024 Educative, Inc. All rights reserved