Anonymous C # and returning filtered properties using JSON

What is the best way to return only a few properties to a JSON result from an IEnumerable collection?

The department object has 7properties. I need only 2 of them in the client. Can I do this using C # anonymous types?

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 } 
+4
source share
3 answers
 var deptnames = depts.Select(d => new { d.DeptID, d.DeptName }); 

Then just use deptnames

0
source

Of course, I serialize anonymous types all the time. This is a reasonable plan.

0
source

Use Linq projection

unverified code

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

Source: https://habr.com/ru/post/1310205/


All Articles