Separate repeated values in a list

Asked

Viewed 977 times

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 of each:

[1,2,3,4,5]

The first list is a List<int> the second can come in any kind of list.

4 answers

14


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 the elements without repetition:

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

See a demonstration here.

  • I did not know this command, but when I read more about it on the Soen, I saw no advantages over the LINQ. http://stackoverflow.com/questions/1247442/when-should-i-use-the-hashsett-type e http://stackoverflow.com/questions/150750/hashset-vs-list-performance

  • @It’s just an alternative way to solve the problem.

11

Use the Distinct to remove duplicated items, generating a new object.

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

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

  • 1

    You don’t need the Select, is unnecessary repetition.

  • Thanks for the tip, edited reply.

  • Now you have my vote =)

7

Use the Distinct to return the different 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();

7

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

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

A functional example can be seen here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.