我有以下内容:
public void ProcessRequest(HttpContext context)
{
string query = context.Request.QueryString["term"];
System.Web.Script.Serialization.JavaScriptSerializer JsonSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
List<Category> Categs = Category.getAll();
var result = from c in Categs where Categs.Contains(c.Name) select c;
context.Response.ContentType = "application/json";
context.Response.Write(JsonSerializer.Serialize(result));
}
尝试返回jQuery UI自动完成的[{label:“Choice1”,value:“value1”},...]列表。我有具有ID和Name属性的类别,我想根据查询字符串和Name属性中的“term”过滤List。我该怎么做?
提前致谢。
答案 0 :(得分:2)
如果您的最终目标是制作[ { label: "Choice1", value: "value1" }, ... ]
的列表并按名称排序,那么这应该有效:
result
.OrderBy(x => x.Name)
.Select(x => new { label: x.Name, value: x.Id }); // create an anonymous type
编辑:您当前的查询:
var result = from c in Categs where Categs.Contains(c.Name) select c;
看起来错了。我认为该查询与仅选择所有Categs
相同。如果您想根据发送的字词进行查询,请在该linq表达式中将c.Name
替换为query
:
var result = from c in Categs where Categs.Contains(query) select c;
答案 1 :(得分:0)
string upperTerm = term.ToUpper();
var result = Category.getAll()
.Where(c => c.Name.ToUpper().Contains(upperTerm))
.Select(c => new { label = c.Name, value = c.Id });
然后JSON序列化result
。