Recognize duplicate items in a list

Asked

Viewed 10,876 times

5

I’m getting a list of items in my action

public ActionResult New(List<Itens> Itens)
{
   return View();
}

How do I recognize which items are duplicated on that list?

  • What criteria should be used to know if an item is duplicated??... for example, when Item1.Id is equal to Item2.Id (I’m kicking)

3 answers

5

The Morelinq package has the great list extension called DistinctBy:

var distinctList = Itens.DistinctBy(x => x.UmaPropriedadeQualquer).ToList();

Now, if you want to know just who repeated, it would be something like:

var repetidos = Itens
                 .GroupBy(x => x.UmaPropriedadeQualquer)
                 .Where(g => g.Count() > 1)
                 .Select(g => g.Key)
                 .ToList();

4

I could just post the link to the OS.en but I find it interesting that we have the answer here.

var list = new List<string> { "a", "a", "b", "b", "r", "t" };

var distinct = new HashSet<string>();    
var duplicates = new HashSet<string>();

foreach (var s in list)
    if (!distinct.Add(s))
        duplicates.Add(s);

// distinct == { "a", "b", "r", "t" }
// duplicates == { "a", "b" }

Only the duplicates

List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };

var dups = list.GroupBy(x => x)
    .Where(x => x.Count() > 1)
    .Select(x => x.Key)
    .ToList();

4

First you can group all the items given a grouping criterion... and then you put each grouping inside a dictionary:

var dicionarioDeArrays = lista
    .GroupBy(x => x)
    .ToDictionary(x => x.Key, x => x.ToArray());

Then we can filter the created dictionary, to return only groups that have an X number of elements, in the case > 1:

var listaDeDuplicatasAgrupadasEmArrays = dicionarioDeArrays
    .Where(x => x.Value.Length > 1)
    .Select(x => x.Value)
    .ToList();

The advantage of this approach is that it is extremely flexible... you can for example:

  • group using a property:

    // agrupar pelo nome das pessoas (caso os itens sejam pessoas)
    .GroupBy(x => x.NomeDaPessoa)
    
  • filter through different quantities:

    // quero pegar os trigêmeos (ou seja, 3 irmãos com o mesmo pai)
    .GroupBy(x => x.Pai)
    
    // ... e depois na hora de verificar, quero apenas os grupos com 3
    .Where(x => x.Value.Length == 3)
    

Browser other questions tagged

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