Robbie Mills Robbie Mills - 23 days ago 7
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
{
[Key]
public int TradeContactId { get; set; }

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

}

public class Region
{
[Key]
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())
.Contains(searchString.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

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

TradeContacts
.Where(s => s.Regions.Select(x => x.Name.ToUpper())
.Contains(searchString.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.