Counting results from a search string MVC 3? - visual-studio-2010

I am using MVC3 and have done a search facility in my controller.I have used the model first approach , what I want to be able to allow the user to search for results that contain the given keyword(s) in the data.
If there are no matches to the search term then display an appropriate message.
If there are matching stories:
Display a message like “7 items match your search criteria: 'XXXXX'”
Any help would be much appreciated , Thanks
would it be something like this but with use of the ViewBag to display a message?.
if (!String.IsNullOrEmpty(SearchString))
News = News.Where(s => s.Headline.Count(SearchString));
}

You need to use string.Contains for partial string matching:
var matchingResults = News.Where(s => s.Headline.Contains(searchString));
int count = matchingResults.Count();
if(count == 0)
{
//no matches
}
else
{
//display message
}

Related

Do we have anything like contains in Unified search?

I have this line of code
query = query.Filter(i =>
(
!i.MatchTypeHierarchy(typeof(InfoPage))
| (((InfoPage)i).SearchSubsection().Exists()
& ((InfoPage)i).GetSearchSubSection().Contains(SOMETHING))
)
); // I want to check if it contains
I want to check if there is anything like a string contains a substring in FIND query. 
Thanks for help in advance. :)
First things first, you are casting to InfoPage which indicates that you shouldn't be using Unified search, instead use the typed search feature.
Second, contains would typically be referred to as wildcard search.
I wrote a typed search wildcard method a while ago, see https://www.herlitz.io/2016/09/19/episerver-find-wildcard-searching/
public static class SearchExtensions
{
public static IQueriedSearch<T> WildCardSearch<T>(this ITypeSearch<T> search, string query)
{
return search.For<T>(query, q => q.Query = string.Concat("*", query, "*"));
}
}
Usage example
var result = SearchClient.Instance.Search<InfoPage>()
.WildCardSearch(query)
.OrderByDescending(x => x.Name)
.FilterForVisitor()
.GetContentResult();

vuetify v-data-table custom-filter questions

I wanted to build a custom-filter for my v-data-table (containing books) which
allows to narrow down search results by entering multiple space separated search terms
separates compound words with hyphens into separate search terms
all search terms should appear in the item, but they can appear in different columns/props, so searching for "tolkien hobbit" would give you back a book with title "The Hobbit" and author "J.R.R. Tolkien"
I figured that using "value" in the customFilter function would require all of the search terms to appear in the same prop, so I used item instead, but vuetify gives the complete item to the filter function, not only the filterable headers of the data table, which will yield unwanted search results, so I'm re-initializing the item to get rid of unwanted props.
methods: {
customFilter(value, search, item) {
item = {
number: item.number,
title: item.title,
author: item.author
};
const haystack = Object.values(item).join().toLowerCase();
let s = search.toString().toLowerCase();
let needles = s.replace('-',' ').split(' ');
return needles.filter(needle => haystack.indexOf(needle) >= 0).length == needles.length
}
}
My questions
Is there a way to tell vuetify to only give the filterable header props to the custom-filter as item?
if not, is there a better way to get rid of unwanted props than re-initializing? (destructuring with spread operator also works, but is longer and eslint nags about unused vars)
Is there maybe even a way to realize my requirements with "value" instead of "item"? (I don't see how)
Answering my own questions:
No, you can't tell vuetify to pass only specific props of the item to the custom filter, you just pass the item object
I get rid of unwanted props by filtering / reducing now
value only gives you one value, presumably it defaults to the first column, but I'm not 100% sure
My solution now:
methods: {
itemFilterMultipleSearchTermsAnd(value, search, item) {
const nonSearchableColumns = ["excludedPropName1", "excludedPropName2"];
const reducedObject = Object.keys(item)
.filter((key) => !nonSearchableColumns.includes(key))
.reduce((res, key) => ((res[key] = item[key]), res), {});
const haystack = Object.values(reducedObject)
.join()
.toLowerCase();
let s = search.toString().toLowerCase();
let needles = s.replace("-", " ").split(" ");
return (
needles.filter((needle) => haystack.indexOf(needle) >= 0).length ==
needles.length
);
}
}

searching by special character on linq

I need a searching process on linq like this. For example, I will make searching on Name column,and user enters "Ca?an" word to textbox. Question mark will e used for sprecial search character for this sitution.
It will search by Name column and, find Canan,Calan,Cazan etc.
I hope I can explain my problem correctly.
Can anyone give me an idea about this linq query. Thank in advance...
You can use this regular expression (if you are using C#) to check for the "Ca?an".
string d = "DDDDDDDDDDCasanDDDDDDDDDD";
Regex r = new Regex(#"Ca([a-zA-Z]{1})an");
string t = r.Match(d).Value;
Output will be:
"Casan"
You have all your colum stored in a database, then do something like:
List<Person> list = new List<Person>(); //Filled
var res = list.Select(x => r.Match(x.Name));
Output will be a IEnumerable with all the "Persons" who contains in the Name "Ca?an", being ? no matter which letter
You need to convert your search-syntax into an existing search-engine - I'd suggest Regex. So the steps will be:
Safely convert the entered search-string into Regex-pattern
Perform the search in Linq on name-property
Solution:
1: Safely convert search string by replacing '?' with Regex-version of wildchar:
var userInput = "Ca?an";
var regexPattern = Regex.Escape(userInput).Replace(#"\?", ".");
2: Perform search in Linq (assuming itemList implements IEnumerable):
var results = itemList.Where(item => Regex.IsMatch(item.Name, regexPattern));
Hope this helps!

How to search an item properly using Hql in my asp.net project?

My query returns searched data but it does'nt search properly
in my table values are
------------------------
Help
------------------------
1 help for abcd
2 help needed before
my Hql query given below
select help from Help help where lower(help.Subject) like lower ('%'" + searchterm + "'%')
when i search for "for" it returns
------------------------
Help
------------------------
1 help for abcd
2 help needed before
I need to return only the first
1. help for abcd
ie: I need to search only the term begins with the search term
Any one please help...
This sounds Like a Word Boundary Problem. Here Is A similar question answered
Search for "whole word match" in MySQL
Sorry, I Have No Idea Why Android Wants To Capitalize All My Words.
Hello frnds i got the solution which works perfectly
at first using the query
select help from Help help
then store the list of help in
var ListofHelps
then
foreach (var item in ListofHelps)
{
if (!string.IsNullOrEmpty(searchterm))
{
var splitsearchterm = Regex.Split(searchterm, #"\s");//split search term
var splittedsubjects = Regex.Split(item.Subject.ToUpper(), #"\s"); //Subject is to be searched
var found = splittedsubjects.Where(x => x.StartsWith(searchterm.ToUpper()));
int datacount = found.Count();
if (splitsearchterm.Count() > 1 && item.Subject.ToUpper().Contains(searchterm.ToUpper()))
{
datacount = 1;
}
if (datacount > 0)
{
Helplist.Add(new HelpViewModel //Helplist is an item in HelpViewModel ie public IEnumerable<MultiSelectList> Taglists { get; set; }
{
Subject = item.Subject,
HelpId = Convert.ToInt32(item.Id),
Content = item.Content
});
}
}
else
{
Helplist.Add(new HelpViewModel
{
Subject = item.Subject,
HelpId = Convert.ToInt32(item.Id),
Content = item.Content
});
}
}
It works for me .Is there any better way to do that

linq query how to take out spaces in strings

I am trying to match a string typed in by a user to a string in a database.
Before I try match them i need to take the spaces out both of them.
how do i do this?
public static Product GetProductbypart(ModelContainer context, string partnumber)
{
var query = from product in context.Products
where product.Partnumber == partnumber
select product;
return query.FirstOrDefault();
}
this is my query which works if the user types in the exact part number. But some users may type it in with too many spaces or too less.
I want to take the partnumber take out the spaces. Then take the product.Partnumber and take of the spaces of that also, to see if there is a match.
Sample inputs:
MC-9a 1a AC24V
MC-9a 50/60Hz
1
123
MC+123-1
F6h67e
_8jj+j7s
string partnumber = partnumber.Replace(" ", String.Emtpy);
var query = from product in context.Products
where product.Partnumber.Replace("", String.Empty) == partnumber
select product;
This removes spaces in the strings product.Partnumber and partnumber. However, if you use linq-to-SQL the part product.Partnumber.Replace(..) won't work. But I'm not sure why you have to remove spaces of the product number in the database. Sounds like inconsistent data to me.
public static Product GetProductbypart(ModelContainer context, string partnumber)
{
partnumber = partnumber.Replace(" ", String.Empty);
var products = from product in context.Products
select product;
foreach(var item in products)
{
if (item.Partnumber != null)
{
item.Partnumber = item.Partnumber.Replace(" ", String.Empty);
if (item.Partnumber == partnumber)
{
var query = from product in context.Products
where product.Id == item.Id
select product;
return query.FirstOrDefault();
}
}
}
return null;
}
This is how i did it
In this case I would think about implementing it a little bit differently. If you need your table only in order to compare it with the user input, you can remove spaces in the database in advance, before running the query. Also there is no point in removing spaces in database, you can do it in client code.
In this case you will be able to use regular Equals and also it should be a little bit more efficient.
I think the best answer here is to not try and figure out how the user entered the data, instead make sure that they entered a valid part number in the first place. Can you provide some form of input format? Even if it means using hyphens where spaces are, you can always remove them before you check, but at least you'll have data in the correct format.

Resources