Robbie Mills Robbie Mills - 11 months ago 60
ASP.NET (C#) Question

Partial linq text searching with Contains

I'm trying to do a text search on a partial property match on related entities.

My entities are:

public class TradeContact
public int TradeContactId { get; set; }

public virtual ICollection<Region> Regions { get; set; }


public class Region
public int RegionId { get; set; }
public virtual ICollection<TradeContact> TradeContacts { get; set; }

My goal is that if a TradeContact has the following regions: Sydney, Brisbane, Darwin, then I should be able to search for 'Syd' to retrieve that TradeContact record.

Currently I'm searching like this:

TradeContacts = TradeContacts
.Where(s => s.Regions.Select(x => x.Name.ToUpper())

This code finds full matches, so 'Sydney' will return my TradeContact, but it doesn't work on partial matches.

What have I done wrong?

Evk Evk
Answer Source

It's important to understand why current approach does not work.

.Where(s => s.Regions.Select(x => x.Name.ToUpper())

If translate that to human language, it would be: give me Contacts where the list of Regions contains region with the Name equal to searchString. So Contains you use is not String.Contains, it's IEnumerable.Contains:

var regionNames = new List<string>();
var match = regionNames.Contains(searchString);

As you see, that indeed matches only when region name equals your search string.

TradeContacts.Where(s => s.Regions.
   Any(x => x.Name.ToUpper().Contains(searchString.ToUpper()));

This one is different: give me all Contacts where any region has Name which contains searchString.