Reputation: 10930
I'm trying to select a list which is having another list itself. But the thing is I've needed to use some delimiter to separate my two list
My List is
{
"Order": {
"Items": [
{
"Details": [
{
"Product": "XXX",
"Category": "YYY"
},
{
"Product": "ZZZ",
"Category": "YYY"
}
]
},
{
"Details": [
{
"Product": "AAA",
"Category": "BBB"
}
]
}
]
}
}
My Final output should be like
XXX|YYYY^ZZZ|YYY^AAA|BBB
Currently, I'm using the solution as like below.
StringBuilder output= new StringBuilder();
string delimiter = "";
foreach (var items in order.Items) {
output.Append(delimiter);
output.Append(string.Join("^",items.Details.Select(l => l.Product+"|"+l.Category)));
delimiter = "^";
}
But this is not the best option. Please help to find the good one.
Upvotes: 1
Views: 685
Reputation: 43886
You can use a single string.Join
with LINQ's SelectMany
:
string result = string.Join("^", order.Items.SelectMany(
item => item.Details.Select(detail => $"{detail.Product}|{detail.Category}")));
This goes through all Details
of all Items
and creates your "Product|Category" strings. Then these strings are all joined with "^" as delimiter.
I don't know your criteria for "good". If you find this readable and think your co-workers will also understand it, I guess it's good. There maybe more efficient ways (in terms of consumed time), but I think this will only be a real matter if you have billions of Details
or need to execute it twice per millisecond.
Upvotes: 6