Home > Software design >  Check if a specific value appears more than once in a table with a LINQ query
Check if a specific value appears more than once in a table with a LINQ query

Time:11-12

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

  var res = differentNames >= 2;
  • Related