c# - 将另一个列表中的列表转换为列表在 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(); });
收到此错误。
无法将匿名方法转换为类型“转换器,字符串>”,因为参数类型与委托参数类型不匹配
解决方案
使用SelectMany
而不是Select
:
List<string> list = CallingUser.UserOrganizations
.SelectMany(x => x.Roles.Select(y => y.RoleId.ToString()))
.ToList();
SelectMany
展平嵌套的集合。
此外,您可以只使用集合中的ToString()
每个int
,而不是稍后转换它们。
推荐阅读
- python - 将内部列表展开为平面列表
- html - 在导航栏中实现搜索栏?
- javascript - JavaScript:复制没有格式的文本,但保留链接
- github - 如何在 GitHub 上找到特定的标签/发布?
- angular - agora.io Angular 10 中出现错误网关/CORS 错误,因为无法开始录制
- algorithm - 在 Elixir 的嵌套映射中交换键
- javascript - 如何在 html 中获取#document 下的元素?
- r - 使用某些行的新信息更新数据框,但同时保留所有旧信息
- mime-types - .NET 5 不正确的响应 MIME 类型。预期的“应用程序/wasm”
- redux - 如何将 Props 数据从渲染传递到 redux 中的 handleSubmit 函数