将一系列序列展平为单个序列(List<Object> 中的 List<string> 包含该 List<string>)

esa*_*ain 2 c# linq .net-6.0

我正在尝试将一些字符串列表提取到单个列表中。首先我有这门课

public class Client
{
  public string Name { get; set; }

  public List<string> ApiScopes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

因此,我得到的响应是 a List<Client> ,我的目的是将所有客户端的范围放入一个列表中而不循环我已经通过 LINQ 尝试过:

 var x = clients.Select(c=> c.AllowedScopes.Select(x => x).ToList()).ToList();
Run Code Online (Sandbox Code Playgroud)

这返回一个List<List<string>>,我只想将所有这些放入一个不同的字符串列表中。

Jon*_*eet 6

听起来像您想要的SelectMany(将一系列序列展平为单个序列),Distinct如果您需要一个列表,其中每个范围仅出现一次,即使它存在于多个客户端:

var scopes = clients.SelectMany(c => c.ApiScopes).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

这假设Client.ApiScopes永远不为空。如果它可能为空,您需要做更多的工作:

var scopes = clients
    .SelectMany(c => ((IEnumerable<string>) c.ApiScopes) ?? Enumerable.Empty<string>())
    .Distinct()
    .ToList();
Run Code Online (Sandbox Code Playgroud)