Arianule
Arianule

Reputation: 9063

Advice on basic Search Function

I have a basic search function where I want to find a product according to the title(name) of the product.

rep.GetDomainObjectsByType("Visuals Product");
    var visualsProducts = rep.DomainObjects;

prodSearched = (from p in visualsProducts
                            from pf in p.DomainObjectFields
                            where pf.FieldName == "Product Title" && pf.FieldValue.Contains(txtSearchValue)
                            select p).Distinct().ToList();

It works fine when entire title is entered such as 'The pros and cons of hitchiking'

How can I alter the query so as to return the title on partial matches only such as 'Pros and Cons'

regards

Upvotes: 0

Views: 86

Answers (2)

kenchilada
kenchilada

Reputation: 7559

In your example, are you overlooking that "pros and cons" and "Pros and Cons" have mixed case?

There are a few different ways to ignore case. Here is one:

var foo = "The Pros and Cons";
bool matched = foo.IndexOf("pros and cons", StringComparison.OrdinalIgnoreCase) >= 0;

Some other options include 1) lowercase or uppercase both strings before comparing them, or 2) use CultureInfo and CompareInfo, or 3) use case-insensitive regular expression matching.

Upvotes: 1

Knaģis
Knaģis

Reputation: 21495

Your code is already using the String.Contains() method that looks for a substring. The issue with your sample test case is more likely to be associated with the casing of the search string.

Usually this would be handled at the data source, for example, by setting Case Insensitive collation to the database column.

Alternatively you can rewrite the query to use

&& pf.FieldValue.ToUpper().Contains(txtSearchValue.ToUpper())

It is possible to use

&& pf.FieldValue.IndexOf(txtSearchValue, StringComparison.OrdinalIgnoreCase) > -1

but this is less likely to be supported by the LINQ provider (for example, Entity Framework does not support it).

Upvotes: 2

Related Questions