【问题标题】:convert List<IEnumerable<int>> to List<int> in C# [duplicate]在 C# 中将 List<IEnumerable<int>> 转换为 List<int> [重复]
【发布时间】:2021-10-20 10:55:13
【问题描述】:

¡嗨!我需要帮助解决这个问题。当我提出请求时,给我的结果是 IEnumerable。我需要将此 IEnumerable 转换为 List。这段代码解决了我的问题,但我正在寻找比这更优雅的解决我的问题的另一种方法。

   var folderCategoriesIds = FolderRepository.GetAll().Where(c => folderIds.Any(y => y == c.Id)).Select(x => x.Categories.Select(y => y.Id)).ToList();
   List<int> list = new List<int>();
   foreach (var item in folderCategoriesIds)
   {
       list.AddRange(item.ToList());
   }

【问题讨论】:

标签: c# .net-core


【解决方案1】:

您可以使用SelectMany 来展平列表。只需在ToList() 之前添加.SelectMany(x =&gt; x) 就可以了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    相关资源
    最近更新 更多