2011-05-23 103 views
0

下面的操作方法,如本文中所描述的JSON数据返回给我的jqGrid:
using-jquery-grid-with-asp.net-mvcLINQ查询为了帮助

我的问题是在此基础上的LINQ查询:

var data = (
    from job in jobs 
    select new 
    { 
     id = job.Id, 
     cell = new List<string>() { job.Industry, job.OccupationName } 
    }).ToArray(); 

为什么细胞列表条目未按预期排序? (工业后跟OccupationName):

我想到的是:


{"total":1400,"page":1,"records":7000, 
"rows":[ 
{"id":"1","cell":{"Industry":"IT","OccupationName":"Administrator"}}, 
{"id":"2","cell":{"Industry":"IT","OccupationName":"Developer"}}, 
{"id":"4","cell":{"Industry":"IT","OccupationName":"Programmer"}} 
]} 

什么,我得到的是:


{"total":1400,"page":1,"records":7000, 
"rows":[ 
{"id":"1","cell":{"Industry":"IT","OccupationName":"Administrator"}}, 
{"id":"2","cell":{"Industry":"Developer","OccupationName":"IT"}}, 
{"id":"4","cell":{"Industry":"IT","OccupationName":"Programmer"}} 
]} 

感谢您的任何建议!

为了清楚起见,整个动作方法:

public ActionResult OccupationList(string sidx, string sord, int page, int rows) 
    { 
     using (var context = Service.EF.GetContext()) 
     { 
      int pageIndex = Convert.ToInt32(page) - 1; 
      int pageSize = rows; 
      int totalRecords = context.sOccupations.Count(); 
      int totalPages = (int)Math.Ceiling((float)totalRecords/(float)pageSize); 

      sidx = "it.[" + sidx + "]"; 

      var jobs = context.sOccupations 
       .OrderBy(sidx + " " + sord) 
       .Skip(pageIndex * pageSize) 
       .Take(pageSize); 

      var data = (
        from job in jobs 
        select new 
        { 
         id = job.Id, 
         cell = new List<string>() { job.Industry, job.OccupationName } 
        }).ToArray(); 

      var jsonData = new 
      { 
       total = totalPages, 
       page = page, 
       records = totalRecords, 
       rows = data 
      }; 

      return Json(jsonData, JsonRequestBehavior.AllowGet); 
     } 
    } 

我目前的解决方案是一个经典的foreach陈述书 但我仍然不知道如何表达这种LINQ查询

IList<JsonRow> data = new List<JsonRow>(); 
    JsonRow jsonRow; 
    foreach (var item in jobs) 
    { 
     jsonRow = new JsonRow(); 
     jsonRow.id = item.Id; 
     jsonRow.cell = new string[2] { item.Industry, item.OccupationName }; 
     data.Add(jsonRow); 
    } 

    class JsonRow 
    { 
     public Guid id { get; set; } 
     public string[] cell { get; set; } 
    } 
+0

您确定你的信息不对? – msarchet 2011-05-23 14:44:14

+0

是的,数据是正确的:) – 2011-05-23 15:24:12

回答

3

你必须按照你的喜好订购“细胞”。

var data = (
     from job in jobs 
orderby job.OccupationName 
     select new 
     { 
      id = job.Id, 
      cell = new List<string>() { job.Industry, job.OccupationName } 
     }).ToArray(); 

您必须检查语法,因为我还没有尝试运行它。 编辑:我试过了,它应该工作。

+0

现在没有运气。语句上方的动态链接查询正常工作。它根据电网参数收集数据。 linq查询应该只能根据过滤的数据创建一个匿名类型。 – 2011-05-23 16:23:43

+0

您总是可以尝试将查询中断为2.将第一部分(在选择new之前)作为一个语句,然后在第二个查询中执行转换。有时候我发现这有助于我在逻辑中发现错误,这些错误在尝试将所有内容作为单个查询进行时并不总是显而易见。 – hermiod 2011-05-23 21:49:29