M
M
mr_blond972018-01-28 03:38:52
Arrays
mr_blond97, 2018-01-28 03:38:52

How to select only duplicate elements from an array?

Given an array: You need to get an array in which there will be only repeating elements:
var a = new[] { 1, 1, 2, 3, 3, 4, 4, 5 };
var a = new[] { 1, 3, 4 };

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Ander, 2018-01-28
@mr_blond97

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
  public static void Main()
  {
    var a = new[] { 1, 1, 2, 3, 3, 4, 4, 5 };
    var r = a.Where(x => a.Count(n => n == x) > 1).Distinct();
    
    foreach (var item in r)
    {
      Console.WriteLine(item);
    }
  }
}

1
3
4

E
Evgeny, 2018-01-29
Maltsev @loqiue

a.GroupBy(x => x)
  .Where(x => x.Count() > 1)
  .Select(x => x.First())
  .ToList()
  .ForEach(Console.WriteLine);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question