I want to get record by using .Contains()
var question= "";
var allLanguage = new List<USerLanguage>()
{
new USerLanguage(){LanguageName="English (United States)", LanguageCode="en-US"},
new USerLanguage(){LanguageName="German (Germany)",LanguageCode="de-DE"},
new USerLanguage(){LanguageName="French (France)", LanguageCode="fr-FR"},
};
var language = allLanguage.Where(r => r.LanguageName.ToLower().Contains(question)).ToList();
Now when i pass the question as "change language to french"
i am not getting any record but when i pass the question as only "french"
then i am getting the record.
How to get the correct record by passing the question as "change language to french"?
Update - I want to pass a sentence like change language to french
and i want to take the word french
and match it with the LanguageName
property of USerLanguage
object
CodePudding user response:
Assuming you're trying to simply return all UserLanguage objects that contain the language mentioned in the question you could do the following:
Update the UserLanguage object so you have a new property that contains the Country. Remove the country from the LanguageName. I've set this as a string but it could be a Country object with 'Name', iso codes etc. You could then move the LanguageCode out as presumably that would match the country code which could now be housed in the Country object:
public class UserLanguage
{
public string LanguageName { get; set; }
public string LanguageCode { get; set; }
public string Country { get; set; }
// any other properties you might have
}
Using an object like this will then allow you to search the question to see if it contains any of the UserLanguage.LanguageName 's:
var culture = CultureInfo.CurrentCulture;
var language = allLanguage.Where(l => culture.CompareInfo.IndexOf(question, l.LanguageName, CompareOptions.IgnoreCase) >=0);
Case Insensitive comparison found here: Case insensitive 'Contains(string)'
One thing to note is that this means you could potentially return multiple languages with that language. Using French there are plenty of countries that have French as the main language.
Update
If you really don't want to alter the UserLanguage object then you can split the LanguageName on a delimiter. However, I think that your current option would be to split on white space, which could cause problems with some languages like 'Mandarin Chinese'. It would really depend on how you're populating that list. A safer bet might be to always assume the country is in brackets, and if so you could do this:
var language = allLanguage.Where(l => culture.CompareInfo.IndexOf(question, l.LanguageName.Split('(')[0].Trim(), CompareOptions.IgnoreCase) >=0);
This checks if the question contains anything that matches the LanguageName once it's been split at the first bracket, taken the first part (hence the 0 index) and removes any trailing white space from that first part.