2010-05-19 94 views
4

什么是仅向JSON返回少量属性的最佳方式集合IEnumerable的结果是什么?C#匿名并使用JSON返回已过滤的属性

部门对象有7个属性我只需要其中2个在客户端。我可以使用C#匿名类型来做到这一点吗?

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 
    } 

回答

0
var deptnames = depts.Select(d => new { d.DeptID, d.DeptName }); 

就用deptnames

0

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

0

使用LINQ投影

未经测试的代码

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

对我来说很好。 – 2010-05-19 07:49:19