Separate repeated values from a list

14

I have a list like this:

[1,1,1,2,2,1,5,3,4,3,4]

How to generate a new list with only one value each:

[1,2,3,4,5]

The first list is List<int> second can come in any type of list.

    
asked by anonymous 29.03.2017 / 19:55

4 answers

13

By mathematical definition, a set is a structure in which each element appears only once. In C #, a set is represented by HashSet<T> .

Generating a HashSet<int> from your list, you will have elements without repeating:

var conjunto = new HashSet<int>(lista);

View a demo here .

    
29.03.2017 / 20:17
11

Use Distinct to remove duplicate items, generating a new object.

List<int> novaListaDeInteiros = listaDeInteirosVelha.Distinct().ToList();

This will return a List<int> sequence filled without repeating the data.

    
29.03.2017 / 20:00
7

Use Distinct to return the various elements from your list.

using System.Linq;

List<int> lista = new List<int> { 1, 1, 1, 2, 2, 1, 5, 3, 4, 3, 4 } ;
lista.Distinct();
    
29.03.2017 / 20:00
7

The Distinct function of Linq deletes duplicate data from a list in the .Net Framework:

var lista = new List<int> {1,1,1,2,2,1,5,3,4,3,4};
var listaSemDuplicidade = lista.Distinct();

A working example might be seen here .

    
29.03.2017 / 20:04