如何返回取决于字段参数的匿名类型,其中列出了必须包含在匿名类型中的属性?任务实体有20多个属性,客户希望收到不同的属性组合。
public class Test
{
public class Task
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
//... more 20 properties
}
public List<Task> Tasks = new List<Task>();
public Test()
{
Tasks.Add(new Task { Id = 1, Name = "Task #1", Description = "Description task #1" });
Tasks.Add(new Task { Id = 2, Name = "Task #2", Description = "Description task #2" });
Tasks.Add(new Task { Id = 3, Name = "Task #3", Description = "Description task #3" });
}
public IEnumerable<object> GetAllTasks(string fields)
{
//if fields == 'Id,Name' then return anonymous type new { Id = t.Id, Name = t.Name }
return Tasks.Select(t => new { Id = t.Id, Name = t.Name });
//if fields == 'Id,Name,Description' then return anonymous type new { Id = t.Id, name = t.Name, Description = t.Description }
return Tasks.Select(t => new { Id = t.Id, Name = t.Name, Description = t.Description });
}
}