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; }
}
IdSeaLevel有這些可能的期望值:0, 1, 2.
然后需要檢查用戶插入的所有值以防止出現一些不同的值。
假設用戶向我們發送了一個國家(Country類的物件),其串列已填充(并嵌套)。
如何獲取用戶插入的所有值?Distinct IdSeaLevel
我在想:
List<decimal> AllowedIdSeaLevellist = new List<decimal>(new decimal[] { 0, 1, 2 });
現在,我得到了一個區域插入值
HashSet<decimal> SentIdSeaLevelSet = country.States
.Select(s => s.Cities.IdSeaLevel).ToHashSet();
查看
bool badRequest= SentIdSeaLevelSet
.Where(s => AllowedIdSeaLevellist.All(a => a != s)).Any();
uj5u.com熱心網友回復:
.SelectMany 將串列串列映射到單個串列(扁平化)
var allSeaLevels = country.States
.SelectMany(s => s.Cities)
.Select(city => city.SeaLevelId)
.ToHashSet();
要獲得“無效”海平面,您也可以在回圈遍歷海平面時收集它們。
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);
}
uj5u.com熱心網友回復:
這種型別的深層鏈接是SelectMany<T>有用的:
HashSet<decimal> SentIdSeaLevelSet = country.States
.SelectMany(s => s.Cities.Select(c => c.IdSeaLevel)).Distinct().ToHashSet()
我們想要投影IdSeaLevel但是Cities是一個串列,所以在某些時候你需要內部Cities.Select()但它可以在里面或之后SelectMany有效地展平層次結構,以便所有嵌套Cities成為一個串列,以下也可以作業:
HashSet<decimal> SentIdSeaLevelSet = country.States
.SelectMany(s => s.Cities).Select(c => c.IdSeaLevel).Distinct().ToHashSet()
我更喜歡首先在SelectMany它內部使用投影,因為我們從不需要City物件的任何其他屬性(第一個示例),但不同的應用程式和結構可能會決定第二個運算式的性能更好。
對于最終比較,您的邏輯看起來沒問題,比較串列的另一種方法是使用 except:
bool badRequest= SentIdSeaLevelSet
.Except(AllowedIdSeaLevellist).Any();
這在功能上等同于您之前的比較并且有效,因為被比較的集合的型別是相同的,運行時可能會稍微快一點,但在這個級別上,您可以根據代碼可讀性做出決定,這本身就是一個主觀主題,但我當我們比較串列時,特別喜歡 except 版本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/392396.html
