我应该如何 return 来自一个 Controller Action 的两个对象列表?

How should I return two lists of objects from one Controller Action?

我有两个来自同一对象的不同列表。我想同时获得这两个作为单独的列表,或者在返回 JSON 对象时加入这两个相同的列表。

这是我的代码。

List<User> userEntity = users.Where(s => s.Id == Id).ToList();

var GetUserNames = userEntity.SelectMany(s => s.Names.Select(u =>
    new
    {
        Name = u.Name,
        Id = u.Id
    })).ToList();

var GetProfile = userEntity.SelectMany(s => s.Profile.Select(u =>
    new
    {
        Name = u.Name,
        Id = u.Id
    })).ToList();

return Json(GetUserNames, JsonRequestBehavior.AllowGet);

你可以使用 GetUserNames.Concat(GetProfile).

List<User> userEntity = users.Where(s => s.Id == Id).ToList();

var GetUserNames = userEntity.SelectMany(s => s.Names.Select(u =>
    new
    {
        Name = u.Name,
        Id = u.Id
    })).ToList();

var GetProfile = userEntity.SelectMany(s => s.Profile.Select(u =>
  new
  {
      Name = u.Name,
      Id = u.Id
  })).ToList();

return Json(GetUserNames.Concat(GetProfile) , JsonRequestBehavior.AllowGet);

Enumerable.Concat Method

根据评论更新

创建一个 class 并枚举:

public class NameId
{
    public string  Name {get;set;}
    public string  Id {get;set;}
    public ThisType Type { get; set; }
}

public enum ThisType
{
   Username,
   Profile
}

然后 return 改为:

List<User> userEntity = users.Where(s => s.Id == Id).ToList();

var GetUserNames = userEntity.SelectMany(s => s.Names.Select(u =>
    new NameId
    {
        Name = u.Name,
        Id = u.Id,
        Type = ThisType.Username
    })).ToList();

var GetProfile = userEntity.SelectMany(s => s.Profile.Select(u =>
  new NameId
  {
      Name = u.Name,
      Id = u.Id,
      Type = ThisType.Profile
  })).ToList();

return Json(GetUserNames.Concat(GetProfile) , JsonRequestBehavior.AllowGet);

我更愿意以不同的方式执行此操作:returned 项目是不同的类型。 return 不是 return 带有类型鉴别器的裸 JSON 列表,而是 return 多属性 JSON 对象:

return Json(new 
{ 
    Names = GetUserNames, 
    Profiles = GetProfile 
}, JsonRequestBehavior.AllowGet);

您的 returned JSON 将 {Name, Id} 对象分为它们的类型,草图形式:

{ 
  Names: [
   {Name:"UserName", Id:"3"}, 
   {Name:"OtherUser", Id: "4"}
  ],
  Profiles: [
   {Name:"Normal", Id:"1"}, 
   {Name:"Admin", Id: "99"}
  ]
}

在大多数 JSON.Net 客户端解析场景中(即使用来自 WPF 智能客户端的 WebAPI),自动映射(例如来自 RestSharp)将允许您将其反序列化为 class形式

public class NameId
{
     public int Id {get; set;}
     public string Name {get; set;}
}

public class UserNamesResponse
{
     public List<NameId> Names {get; set;}
     public List<NameId> Profiles {get; set;}
}

与交错列表相比,这可能更方便、更清晰,交错列表必须被过滤到单独的列表中以进行绑定……(或者通过过滤类型转换器馈送,但性能会受到影响 UI 绑定层...)