gpt4 book ai didi

c# - 如何返回自定义匿名类型?

转载 作者:太空狗 更新时间:2023-10-29 23:40:00 26 4
gpt4 key购买 nike

如何返回取决于字段参数的匿名类型,其中列出了必须包含在匿名类型中的属性?任务实体有 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 });
}
}

最佳答案

希望对你有帮助

public List<Task> Tasks = new List<Task>();

public void 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 ActionResult Index()
{
Test();

return Json(GetAllTasks(), JsonRequestBehavior.AllowGet);
}

public IEnumerable<object> GetAllTasks()
{
return Tasks.Select(GetTask);
}

private object GetTask(Task task)
{
dynamic expandoObject = new ExpandoObject();
//your if statment block
if (task.Id == 1)
{
expandoObject.Id = task.Id;
}

expandoObject.Name = task.Name;
expandoObject.Description = task.Description;

var dictionary = expandoObject as IDictionary<string, object>;
return dictionary.ToDictionary(item => item.Key, item => item.Value);
}

查看结果:

[
[
{
"Key":"Id",
"Value":1
},
{
"Key":"Name",
"Value":"Task #1"
},
{
"Key":"Description",
"Value":"Description task #1"
}
],
[
{
"Key":"Name",
"Value":"Task #2"
},
{
"Key":"Description",
"Value":"Description task #2"
}
],
[
{
"Key":"Name",
"Value":"Task #3"
},
{
"Key":"Description",
"Value":"Description task #3"
}
]
]

关于c# - 如何返回自定义匿名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14953120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com