Check two or more occurrences of list element (lambda / linq)

2

I have the following list<t>

listCard;

inside it I have the following values:

[0]:7720890002560
[1]:7720890002560
[2]:7777777002560
[3]:7720890002560
[4]:7720444402560
[5]:7720777002560
[6]:7728888802560
[7]:7727777702560

I need to check for more than one occurrence of a given value, for example, 7720890002560 (in my example above I have 2 occurrences of this value)

Just to clarify note I'll get the type return

if (ExisteMaisQueUm) continue; 
    
asked by anonymous 06.04.2017 / 20:55

3 answers

1

Solved this way:

if (listCard.Count(_ => _.ToString().Equals(card)) > 1) continue;
    
06.04.2017 / 21:14
1

Another way to solve:

if (listCard.Count(x => x == card) > 1) continue;
    
06.04.2017 / 22:01
1

See this form using linq by method syntax:

var listCard = new List<string>
{
    "7720890002560",
    "7720890002560",
    "7777777002560",
    "7720890002560",
    "7720444402560",
    "7720777002560",
    "7728888802560",
    "7727777702560"
};

var valoresRepedidos = listCard.GroupBy(s => s).SelectMany(group => group.Skip(1)).ToList();

WriteLine($"Ocorrencias: {valoresRepedidos.Count()}\n");

valoresRepedidos.ForEach(s => WriteLine(s));

Output:

  

Occurrences: 2

     

7720890002560
  7720890002560

If you do not have any value repeated, the variable valoresRepedidos will have 0 items.

>     
06.04.2017 / 22:09