代码之家  ›  专栏  ›  技术社区  ›  Spock

C匿名并用JSON返回过滤属性

c#
  •  4
  • Spock  · 技术社区  · 16 年前

    从集合IEnumerable仅返回几个属性到JSON结果的最佳方法是什么?

    Department对象有7个属性,在客户机中我只需要其中2个。我可以使用匿名类型吗?

        public class Department
        {
            public string DeptId { get; set; }
            public string DeptName { get; set; }
            public string DeptLoc1 { get; set; }
            public string DeptLoc2 { get; set; }
            public string DeptMgr { get; set; }
            public string DeptEmp { get; set; }
            public string DeptEmp2 { get; set; }            
        }
    
    
    
        [HttpGet]
        public JsonResult DepartmentSearch(string query)
        {
    
            IEnumerable<Department> depts = DeptSearchService.GetDepartments(query);
    
            //Department object has 15 properties, I ONLY need 2 (DeptID and DeptName) in the view via returns JSON result)
    
    
            return Json(depts, JsonRequestBehavior.AllowGet); // I don’t want all the  properties of  a department object
       }
    
    3 回复  |  直到 15 年前
        1
  •  0
  •   tzaman    16 年前
    var deptnames = depts.Select(d => new { d.DeptID, d.DeptName });
    

    然后就用 deptnames

        2
  •  0
  •   Sky Sanders    16 年前

    当然,我json一直在序列化匿名类型。是个明智的计划。

        3
  •  0
  •   Raj Kaimal    16 年前

    使用LINQ投影

    未经测试的代码

    var deptsProjected = from d in depts
                        select new {
                           d.DeptId,
                           d.DeptName
                        };
     return Json(deptsProjected , JsonRequestBehavior.AllowGet);