user7849697
user7849697

Reputation: 597

Check if a specific value appears more than once in a table with a LINQ query

I tried with this but it is not what I want :

var result = myList
    .GetQueryable()
    .GroupBy(g => g.Name)
    .Where(w => w.Name == "myName")
    .AnyAsync(a => a.Count() > 1);

This should return true if it finds more then 1 record with the name "myName" and false if at most one name "myName" is found.

I get compile time error in the Where clause. But I need to check for a specific value.

Any idea?

Upvotes: 1

Views: 977

Answers (3)

Ran Turner
Ran Turner

Reputation: 18116

  var differentNames = myList.Select(l => l.name == "myName")
                              .Distinct()
                              .Count();

  var res = differentNames >= 2;

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

There's no need in GroupBy (which will group the entire myList) and in Count() (if we have, say, 123456789 "myName" items then Count() will count them all and only then compare with 1):

var result = myList
  .Where(item => item.Name == "myName") // items of interest only
  .Skip(1)                              // Skip the first one
  .Any();                               // do we have second? 

we filter items of interest: Where, Skip the very first of them and check if we have second one.

Upvotes: 5

Leandro Bardelli
Leandro Bardelli

Reputation: 11598

bool result = (myList.Where(item => item.Name == "myName").Count() > 1)

Upvotes: 0

Related Questions