3

I have been working out for a case-insensitive search for hours and I still can`t find a solution...

I have data stored in MongoDB and formatted like this :

{
  id: 12345,
  name: "foo",
  area: ["US","California"],
  ...
}

And I wanna use query to find results, as a list, that area partially matches the area string. For example, if I want to find people who are in us, with lower case. My method looks like this:

public async Task<IEnumerable<Restaurant>> GetByArea(string area)
{
     var result = await _context.Users
          .Find(user => user.Area.Contains(area))
          .ToListAsync();

     try
     {
          return result;
     }
     catch (Exception e)
     {
          return null;
     }
}

How should I modify my code to conform case-insensitive search? The IEqualityComparer's methods won't be translated to MongoDB query.

smolchanovsky
  • 1,775
  • 2
  • 15
  • 29
Liu Junhan
  • 203
  • 3
  • 8

2 Answers2

2

I'm not sure it would work, but you can try to use the method Any:

var result = await _context.Users
    .Find(user => user.Area.Any(item => item.ToLower() == area.ToLower()))
    .ToListAsync();
smolchanovsky
  • 1,775
  • 2
  • 15
  • 29
  • Thank you! that actually works! I was stuck on how to use StringComparer and not looked back the simple way!! – Liu Junhan Jan 09 '20 at 21:55
0

Would something like this help?

(user => user.Area.Contains(area, StringComparer.InvariantCultureIgnoreCase))
Seva
  • 1,631
  • 2
  • 18
  • 23