【问题标题】:Convert a list inside another list to list<string> in C# [duplicate]将另一个列表中的列表转换为 C# 中的 list<string> [重复]
【发布时间】:2020-09-24 14:38:22
【问题描述】:

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

以下是列表属性。

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.net asp.net-core


    【解决方案1】:

    使用SelectMany 而不是Select

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

    SelectMany 将嵌套集合展平。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-29
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      相关资源
      最近更新 更多