我有以下課程:
public class EquipmentListFilter
{
public string ColumnName { get; set; }
public string Keyword { get; set; }
public string Operand { get; set; }
public string FilterType { get; set; }
}
public class EquipmentFilterPack
{
public string[] ColumnNames { get; set; }
public string[] keywords { get; set; }
public string[] FilterTypes { get; set; }
public string[] Operands { get; set; }
}
我將EquipmentFilterPack物件作為我的 API 中的輸入。我必須映射EquipmentFilterPack到EquipmentListFilter. 最后的結果應該是List<EquipmentListFilter>。
例如:
[
{
ColumnName = "C1",
Keyword = "kw1",
Operand = "AND",
FilterType = "?IS"
},
{
ColumnName = "C2",
Keyword = "kw2",
Operand = "AND",
FilterType = "?IS NOT"
},
...
]
一個類似的執行緒是here。
如何創建最終串列?有沒有 LINQ 解決方案?
uj5u.com熱心網友回復:
如上所述,這四個屬性陣列具有完全相同的長度,最簡單的方法是您可以使用for回圈來迭代并通過注釋中涵蓋的索引獲取元素。
另一種方法是通過 LINQ 執行 CROSS JOIN:
查詢運算式
List<EquipmentListFilter> filters = (from a in pack.ColumnNames
from b in pack.keywords
from c in pack.FilterTypes
from d in pack.Operands
select new EquipmentListFilter
{
ColumnName = a,
Keyword = b,
FilterType = c,
Operand = d,
}).ToList();
演示@.NET Fiddle
uj5u.com熱心網友回復:
有一些 nuget 包可以幫助你喜歡 imapper 和 newtonsoft。
如果你自己做,你必須:
- 構建一個 for 回圈。
- 從 EquipmentFilterPack 的陣列屬性中獲取最大長度。
- 使用“長度”作為迭代計數來迭代屬性。
- 通過不繼續迭代長度小于當前迭代索引的陣列來保護自己免受 indexoutofbound 例外的影響。
- 創建將在 for 回圈 (List) 之外的 EquipmentListFilterList。
- 在每次迭代中創建 EquipmentListFilter 物件,并從 EquipmentFilterPack 屬性中提供其屬性。
- 將每個新創建的 EquipmentListFilter 添加到 EquipmentListFilterList。
LINQ 解決方案也是可行的,盡管它會更加復雜。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/515613.html
標籤:C#列表林克
上一篇:如何創建動態Linq運算式
