ā Foreach on two different lists
Hey i would like to know how to do a foreach loop for these two different lists where it can print out "aBook" and "aAuthor" in the same line, something like
Console.WriteLine(aBook + " by " aAuthor)
thank you in advance!10 Replies
Well, it would be best if you simply structured your code differently
Make a class
Book
that has a Title
and Author
property
Have a list of those objects
And loop over that
If you really want to iterate over two lists at the same time, though, you'll have to do it with a for
loop
And take precautions in case one list is shorter than the otherinteresting
i tried to make a class but i was struggling to get user input to add a book
It shouldn't be hard
Enumerable.Zip Method (System.Linq)
Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
Well, sure, you can zip them
But the proper way to handle related data is... objects
Just another way to do exactly what you asked for. But yes, do a structure if you can
Classes, structs, records, etc
I'd say use a class or a record
Structs are used rarely, and only when you know you actually need a struct
omg
thank you very much
š
You can even put complex objects in other objects.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.