C
C#2mo ago
workani

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
Pobiega
Pobiega2mo ago
What does your current string look like?
workani
workaniOP2mo ago
3kg Apple 2l Milk 1 Jogurt
Pobiega
Pobiega2mo ago
okay, and you want to split that into 3 items, I assume? so single string into a list with 3 items of your ShoppingList type
workani
workaniOP2mo ago
Not exactly, my string can contain different amount of items. I want to use this logic in my web app
Pobiega
Pobiega2mo ago
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
workani
workaniOP2mo ago
I will use whitespace as my separator
Pobiega
Pobiega2mo ago
You sure about that?
3kg Apple
2l Milk
1 Jogurt
3kg Apple
2l Milk
1 Jogurt
how many items will this string result in, if you use any whitespace as a separator?
workani
workaniOP2mo ago
Oh, then semicolon
Pobiega
Pobiega2mo ago
could I suggest newline? also, why do you go afk for 5 min after every message :p
workani
workaniOP2mo ago
Let’s go with \n Sorry, I’m not at home currently
Pobiega
Pobiega2mo ago
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 expression
D.Mentia
D.Mentia2mo ago
If you can control the input format, probably just make it json, it's much simpler. Otherwise something like
var myObjects = myString.Split('\n').Select(x => new ShoppingItem(x, false));
var myObjects = myString.Split('\n').Select(x => new ShoppingItem(x, false));
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 ShoppingList
Pobiega
Pobiega2mo ago
line ending problem easily fixed by just trimming the strings, which split itself can already do. \r is not a valid newline on its own
workani
workaniOP2mo ago
Okay. And then simply modify my ShoppingItem construct to take in string and bool variable. Correct?
Pobiega
Pobiega2mo ago
¯\_(ツ)_/¯ thats up to you'
Want results from more Discord servers?
Add your server