linq查询顺序帮助

时间:2011-05-23 14:31:00

标签: asp.net-mvc linq json.net

以下操作方法将json数据返回到我的jqGrid,如本文所述:
using-jquery-grid-with-asp.net-mvc

我的问题是基于这个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; }
    }

1 个答案:

答案 0 :(得分:3)

你必须按照自己的意愿订购“细胞”。

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

您必须检查语法,因为我还没有尝试过运行它。 编辑:我试过这个,应该可以。