Question

I am working on a search method, which will be called with Ajax, and updates a Webgrid in Mvc4. The search will go through a list of Project objects, which contains some fields.

One of the fields is Country. And right now my code only checks if the input string contains the search string:

private bool StringStartWith(string input, string searchstring)
{

    bool startwith = false;
    var inputlist = new List<string>(input.ToLower().Split(' ').Distinct());
    var searchList = new List<string>(searchstring.ToLower().Split(' '));

    var count = (from inp in inputlist from sear in searchList where inp.StartsWith(sear) select inp).Count();
    if (count == searchList.Count)
        startwith = true;
    return startwith;
}

But I also want to be able to search by country code. So if I write "DK", it should tell that it is equal to Denmark.

I hope I can get some help for it. Thanks.

//UPDATE!!

iTURTEV answer helped me to make my method work as it should. I just had to update my method as shown here:

        private bool InputStartWithSearch(string input, string searchstring)
    {
        if(searchstring[searchstring.Length-1].Equals(' '))
            searchstring = searchstring.Substring(0,searchstring.Length-2);

        bool startwith = false;
        var inputlist = new List<string>(input.ToLower().Split(' ').Distinct());
        var searchList = new List<string>(searchstring.ToLower().Split(' '));

        if (searchstring.Length == 2)
        {
            var countryCode = new RegionInfo(searchstring.ToUpper()).EnglishName;
            if (inputlist.Any(country => country.ToLower().Equals(countryCode.ToLower())))
            {
                return true;
            }
        }
        var count = (from inp in inputlist from sear in searchList where inp.StartsWith(sear) select inp).Count();
        if (count == searchList.Count)
            startwith = true;
        return startwith;
    }

Thanks a lot.

Was it helpful?

Solution

May be you can use RegionInfo:

// returns Bulgaria
new RegionInfo("BG").EnglishName;

OTHER TIPS

Assuming:

public class Country {
    public int Id { get; set; }
    public string Name { get; set; }
    public string IsoCode { get; set; }
}

Then:

return x.Countries.Where(q => 
    q.Name != null && q.Name.ToLowerInvariant().Contains(text) || 
    q.IsoCode != null && q.IsoCode.ToLowerInvariant().Contains(text));

This will return every Country having text on its name or code. It's important to check for nulls unless you're using [Required] data annotation, if you don't want this to be case insensitive you could remove the .ToLowerInvariant().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top