首页 > 解决方案 > 将另一个列表中的列表转换为列表在 C# 中

问题描述

我在列表中有一个列表,我需要将其转换为字符串列表。

以下是列表属性。

List<UserOrganization> UserOrganizations { get; set; }

public interface UserOrganization
    {
       IEnumerable<UserRole> Roles { get; set; }
    }

public class UserRole
    {
        public int RoleId { get; set; }     
    }

我需要找到所有 RoleId 并将它们返回到字符串列表中。

我尝试了下面的代码,但无法从中获取字符串列表。

 var securityRoleIds= CallingUser.UserOrganizations.Select(x => x.Roles.Select(y=> y.RoleId).ToList()).ToList();
List<string> l2 = securityRoleIds.ConvertAll<string>(delegate(Int32 i) { return i.ToString(); });

收到此错误。

无法将匿名方法转换为类型“转换器,字符串>”,因为参数类型与委托参数类型不匹配

标签: c#asp.netasp.net-core

解决方案


使用SelectMany而不是Select

List<string> list = CallingUser.UserOrganizations
    .SelectMany(x => x.Roles.Select(y => y.RoleId.ToString()))
    .ToList();

SelectMany展平嵌套的集合。

此外,您可以只使用集合中的ToString()每个int,而不是稍后转换它们。


推荐阅读