Let SQL do the filtering for you:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string filter = Request.QueryString["q"];
if (string.IsNullOrEmpty(filter))
{
Response.Redirect("~/Default.aspx");
return;
}
DataTable list = GetCountries(filter);
string json = SerializeCountries(list);
Response.Clear();
Response.ContentType = "text/plain";
Response.Write(json);
Response.End();
}
}
private DataTable GetCountries(string filter)
{
using (var connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString))
using (var command = new SqlCommand("SELECT id, country FROM Country WHERE country Like @filter", connection))
{
command.Parameters.AddWithValue("@filter", "%" + filter + "%");
var table = new DataTable();
var da = new SqlDataAdapter(command);
da.Fill(table);
return table;
}
}
private string SerializeCountries(DataTable countries)
{
var query = from DataRow row in countries.Rows
select new
{
id = Convert.ToString(row["id"]),
name = Convert.ToString(row["country"])
};
return new JavaScriptSerializer().Serialize(query);
}