Distinct

In this chapter you will learn:

  1. How to use Distinct operator
  2. Use Linq Distinct to get the distinct value in an array
  3. Distinct characters in an array

Get to know Distinct operator

Distinct returns the input sequence, stripped of duplicates.

using System;//from j a v  a2  s  .co m
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;


public class MainClass{

   public static void Main(string[] args){   
         String[] First = { "One", "Two", "Two", "Three", "Four" };
         String[] Second = { "Three", "Four", "Five", "Six" };

         var ShowDistinct = First.Distinct();

         // Display the output.
         Console.WriteLine("Distinct:");
         foreach (String ThisElement in ShowDistinct)
            Console.WriteLine(ThisElement);

   }
}

Distinct values in an array

using System;/*from   j  av a2 s. c  om*/
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;

public class MainClass{
   public static void Main(){
            int[] numbers = {1, 1, 2, 3, 3};
            Console.Write(numbers.Distinct());
   }
}

Distinct characters in an array

using System;/* j av a2  s  .c  om*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        char[] distinctLetters = "HelloWorld".Distinct().ToArray();
        string s = new string(distinctLetters);
        Console.WriteLine(s);
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to use ElementAt operator
  2. ElementAt vs ElementAtOrDefault
  3. Use ElementAt to print the fourth number less that 5 in an integer array
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip