在c#中返回动态列表或字典

时间:2014-12-09 09:00:08

标签: c#

我有一个可以返回多个键值对象的函数。我不知道该怎么做。

 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吗?关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:1)

如果我了解你的需要,我会这样做:

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;
    }
}

但正如上面的评论所说,你也可以用一个简单的字典来做这个伎俩。

答案 1 :(得分:1)

使用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
                                 });
    }

但无论如何我建议使用Dictionary。你需要这样的东西:

    public static Dictionary<OrganizationType, UserRoles> GetOrganizationType(User user)
    {
        return user.GetUserRoles().ToDictionary(ur => OrganizationType.Get(ur.organizationTypeId, "1"),
                                                ur => ur);
    }