Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#匿名并返回带有JSON的过滤属性_C# - Fatal编程技术网

C#匿名并返回带有JSON的过滤属性

C#匿名并返回带有JSON的过滤属性,c#,C#,从集合IEnumerable向JSON结果返回几个属性的最佳方法是什么 Department对象有7个属性,我只需要在client中添加其中的2个属性。我可以使用C#匿名类型来实现这一点吗 public class Department { public string DeptId { get; set; } public string DeptName { get; set; } public string DeptLoc1 {

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

Department对象有7个属性,我只需要在client中添加其中的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
   }
公共课部
{
公共字符串DeptId{get;set;}
公共字符串DeptName{get;set;}
公共字符串DeptLoc1{get;set;}
公共字符串DeptLoc2{get;set;}
公共字符串DeptMgr{get;set;}
公共字符串DeptEmp{get;set;}
公共字符串DeptEmp2{get;set;}
}
[HttpGet]
公共JsonResult部门搜索(字符串查询)
{
IEnumerable depts=DeptSearchService.GetDepartments(查询);
//Department对象有15个属性,通过返回JSON结果,我在视图中只需要2个(DeptID和DeptName)
返回Json(depts,JsonRequestBehavior.AllowGet);//我不需要department对象的所有属性
}

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

使用Linq投影

未测试代码

var deptsProjected = from d in depts
                    select new {
                       d.DeptId,
                       d.DeptName
                    };
 return Json(deptsProjected , JsonRequestBehavior.AllowGet); 
然后只需使用
deptnames

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