在 c# 中返回动态列表或字典
本文关键字:列表 字典 动态 返回 | 更新日期: 2023-09-27 18:33:43
我有一个函数可以返回多个键,值对象。我不知道该怎么做。
public static List <String> organizationType(User user)
{
List<String> data = new List<String>();
foreach (UserRoles ur in user.GetUserRoles())
{
OrganizationType ot = OrganizationType.Get(ur.organizationTypeId, "1");
data.Add(ot.Name); // I would need a key here as well
data.Add(ur.roleTypeId);
data.Add(ur.organizationId);
}
return data;
}
我想要的是一些想法
var objs = organizationType(...);
for (var i in objs){
objs[var].Name; // something like this
}
我可以返回 JSON 吗?知道如何做到这一点吗?
如果我了解您的需求,我会这样做:
public static IEnumerable<string[]> organizationType(User user)
{
foreach (UserRoles ur in user.GetUserRoles())
{
OrganizationType ot = OrganizationType.Get(ur.organizationTypeId, "1");
string[] data = new string[] { ot.Name, ur.roleTypeId, ur.organizationId };
yield return data;
}
}
但正如上面的评论中所说,您也可以使用简单的字典来解决问题。
使用 LINQ 查询:
public static IEnumerable<string[]> GetOrganizationType(User user)
{
return from ur in user.GetUserRoles()
let ot = OrganizationType.Get(ur.organizationTypeId, "1")
select new[] {ot.Name, ur.roleTypeId, ur.organizationId};
}
或方法链:
public static IEnumerable<string[]> GetOrganizationType(User user)
{
return user.GetUserRoles()
.Select(ur => new[]
{
OrganizationType.Get(ur.organizationTypeId, "1").Name,
ur.roleTypeId,
ur.organizationId
});
}
但无论如何我建议使用字典。你需要这样的东西:
public static Dictionary<OrganizationType, UserRoles> GetOrganizationType(User user)
{
return user.GetUserRoles().ToDictionary(ur => OrganizationType.Get(ur.organizationTypeId, "1"),
ur => ur);
}