C# 中嵌套列表的 Enumerable.Select 的区别

5 c# linq select distinct

public class Country
{
    public List<State> States { get; set; } = new List<State>();
}

public class State
{
    public List<City> Cities { get; set; } = new List<City>();
}

public class City
{
    public decimal IdSeaLevel { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

IdSeaLevel有这些可能的期望值:0, 1, 2.

然后需要检查用户插入的所有值以防止出现一些不同的值。

假设用户向我们发送一个国家(类对象Country),其列表已填充(并且也嵌套)。

如何获取用户插入的所有值?Distinct IdSeaLevel

我当时想的是:

List<decimal> AllowedIdSeaLevellist = new List<decimal>(new decimal[] { 0, 1, 2 });
Run Code Online (Sandbox Code Playgroud)

现在,我得到一个 Distict 插入值

HashSet<decimal> SentIdSeaLevelSet = country.States
                .Select(s => s.Cities.IdSeaLevel).ToHashSet();
Run Code Online (Sandbox Code Playgroud)

查看

bool badRequest= SentIdSeaLevelSet
    .Where(s => AllowedIdSeaLevellist.All(a => a != s)).Any();
Run Code Online (Sandbox Code Playgroud)

Fab*_*bio 1

.SelectMany将列表列表映射到单个列表(展平)

var allSeaLevels = country.States
   .SelectMany(s => s.Cities)
   .Select(city => city.SeaLevelId)
   .ToHashSet();
Run Code Online (Sandbox Code Playgroud)

要获得“无效”海平面,您也可以在循环海平面时收集它们。

var validSeaLevels = new[] { 0, 1, 2 }.ToHashSet();

var invalidSeaLevels = country.States
   .SelectMany(s => s.Cities)
   .Select(city => city.SeaLevelId)
   .Where(level => validSeaLevels.Contains(level) == false)
   .ToArray();

if (invalidSeaLevels.Any())
{
    return BadRequest(invalidSeaLevels);
}  
Run Code Online (Sandbox Code Playgroud)