您好我正在嘗試根據多個布爾引數過濾專案串列。我有 3 個布爾引數(它們是 UI 中的 3 個復選框):IsTypeA、IsTypeB、IsTypeC。基于這 3 個值,我必須根據專案的列舉屬性(簡稱為“型別”)過濾我的串列。可以選中多個復選框。型別過濾器上方還有另一個過濾器(“in”,“out”),但它正在作業。到目前為止我嘗試過的是:
FilteredDashboardItems = AllItems?.Where(x =>
Destination == "in" ?
(
(IsTypeA == true ? x.Type == Helpers.Enum.A : true)
&&
(IsTypeB == true ? x.Type == Helpers.Enum.B : true)
&&
(IsTypeC == true ? x.Type == Helpers.Enum.C : true)
) :
Destination == "out" ?
(
(IsTypeA == true ? x.Type == Helpers.Enum.A : true)
&&
(IsTypeB == true ? x.Type == Helpers.Enum.B : true)
&&
(IsTypeC == true ? x.Type == Helpers.Enum.C : true)
) : true)?.ToList();
問題是:如果我單獨選中一個復選框(比如說 IsTypeA),則串列會被正確過濾為 A 型別的專案。但是,如果我選中另一個復選框(比如說 IsTypeB)而不是向我顯示 A B 型別過濾串列,則該串列回傳 0 個專案。我該如何解決?
uj5u.com熱心網友回復:
您正在使用 && 這將為您提供兩個過濾器的交集,因此為 0 條記錄。
您需要使用 OR || 以便它顯示滿足任一過濾器的元素。
uj5u.com熱心網友回復:
你需要這樣的東西:
List<int> typesToCheck = new List<int>();
if (IsTypeA) typesToCheck.Add((int)Helpers.A);
if (IsTypeB) typesToCheck.Add((int)Helpers.B);
if (IsTypeC) typesToCheck.Add((int)Helpers.C);
FilteredDashboardItems = AllItems?.Where(x => Destination == "in" ?
(IsTypeA || IsTypeB || IsTypeC ? typesToCheck.Contains(x.Type) : true)
:
Destination == "out" ?
(IsTypeA || IsTypeB || IsTypeC ? typesToCheck.Contains(x.Type) : true)
:
true)?.ToList();
一旦你得到這個表格,我相信你也可以簡化目的地條件
uj5u.com熱心網友回復:
你的情況有點奇怪
IsTypeA == true ? x.Type == Helpers.Enum.A : true
如果IsTypeA不是可空的 bool,則無需將其與true進行比較,因為從邏輯上講,您會得到true == true或false == true,因此您可以離開IsTypeA。
我會重寫你的條件:
FilteredDashboardItems = AllItems?.Where(x =>
Destination == "in" ?
(
(IsTypeA && x.Type == Helpers.Enum.A)
||
(IsTypeB && x.Type == Helpers.Enum.B)
||
(IsTypeC && x.Type == Helpers.Enum.C)
) :
Destination == "out" ?
(
(IsTypeA && x.Type == Helpers.Enum.A)
||
(IsTypeB && x.Type == Helpers.Enum.B)
||
(IsTypeC && x.Type == Helpers.Enum.C)
) : true)?.ToList();
現在我們有了簡單的邏輯:如果至少有一個選擇的型別等于物件型別,那么保留這個物件
uj5u.com熱心網友回復:
在這種型別的問題中,如果串列中有很多項,我會建議將 Linq 寫為 QUERY,而不是方法。
(from item in AllItems
let firstCondition = (IsTypeA && x.Type == Helpers.Enum.A)
let secCondition = (IsTypeB && x.Type == Helpers.Enum.B)
where firstCondition && secCondition
select item)?.ToList();
當您以這種形式撰寫時,您會在 let 部分創建 tmp 變數并節省時間,而且我認為這種形式在復雜邏輯中更具可讀性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510725.html
標籤:C#林克拉姆达
