I have the following classes:
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; }
}
I get the EquipmentFilterPack object as input in my API. I have to map EquipmentFilterPack to a list of EquipmentListFilter. The final result should be List<EquipmentListFilter>
.
For example:
[
{
ColumnName = "C1",
Keyword = "kw1",
Operand = "AND",
FilterType = "ٍIS"
},
{
ColumnName = "C2",
Keyword = "kw2",
Operand = "AND",
FilterType = "ٍIS NOT"
},
.
.
.
]
A similar thread is here.
How can I create the final list? Is there any Linq solution?
CodePudding user response:
As clarified that those four properties arrays have the exact same length, the easiest way is you can use a for
loop to iterate and get the element by an index that has been covered in the comment.
Another approach will be performing CROSS JOIN via LINQ:
Query expression
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();
CodePudding user response:
There are nuget packages that can help you like imapper and newtonsoft.
If you do it yourself, you would have to:
- Build a for loop.
- Get the biggest length from the array properties' of EquipmentFilterPack.
- Use the 'Length' as the iteration count to iterate over the properties.
- Guard yourself from indexoutofbound exception by not continuing iterating over arrays with smaller lengths than the current iterating index.
- Create EquipmentListFilterList that will be outside the for loop, (List).
- Create EquipmentListFilter object in every iteration and feed its properties from the EquipmentFilterPack properties.
- Add every newly created EquipmentListFilter to EquipmentListFilterList.
A LINQ solution is also viable, although it would be more convoluted.