Check two or more occurrences of a listed element (lambda/Linq)

Asked

Viewed 842 times

2

I have the following list<t>

listCard;

within it I have the following values:

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

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

just for clarification note I’ll pick up the return type

if (ExisteMaisQueUm) continue; 

3 answers

1


Solved in this way:

if (listCard.Count(_ => _.ToString().Equals(card)) > 1) continue;

1

Another way to solve:

if (listCard.Count(x => x == card) > 1) continue;

1

See this form using the 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));

Exit:

Occurrences: 2

7720890002560
7720890002560

If you have no value repeated the variable valoresRepedidos will own 0 items.

Source.

Browser other questions tagged

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