Converting a string to a list of objects using only LINQ.
I want to convert my string with a shopping list in it to a list of ShoppingList objects (it contains a bool IsBought and a string Content) using only LINQ. How could I do that?
15 Replies
What does your current string look like?
3kg Apple
2l Milk
1 Jogurt
okay, and you want to split that into 3 items, I assume?
so single string into a list with 3 items of your
ShoppingList
typeNot exactly, my string can contain different amount of items. I want to use this logic in my web app
Okay. Not a problem, as long as the string always has the same separator
ie, something that indicates when an item ends and the next begins
I will use whitespace as my separator
You sure about that?
how many items will this string result in, if you use any whitespace as a separator?
Oh, then semicolon
could I suggest newline?
also, why do you go afk for 5 min after every message :p
Let’s go with \n
Sorry, I’m not at home currently
right, thats what I suggested. newlines are technically whitespace, but so are tabs, normal spaces and... yeah, lets not split on any whitespace, lets split on only newlines.
after that, linq can do its magic. LINQ operates on enumerables, which are basicly sequences. Any collection is also an enumerable
so split your string, which turns it into an array.. then use linq (the
Select
method in particular) to transform your sequence to a different sequence, with each item transformed by your select expressionIf you can control the input format, probably just make it json, it's much simpler. Otherwise something like
but you may have problems with line endings sometimes being
\r\n
or \r
or \n
... also notably, it doesn't make sense for one entry on a shopping list to be a ShoppingListline ending problem easily fixed by just trimming the strings, which split itself can already do.
\r
is not a valid newline on its ownOkay. And then simply modify my ShoppingItem construct to take in string and bool variable. Correct?
¯\_(ツ)_/¯
thats up to you'