C
C#ā€¢10mo ago
Mysel

ā” 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!
No description
10 Replies
Angius
Angiusā€¢10mo ago
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 other
Mysel
Myselā€¢10mo ago
interesting i tried to make a class but i was struggling to get user input to add a book
Angius
Angiusā€¢10mo ago
It shouldn't be hard
// we can use record instead of a class for brevity
record Book(string Title, string Author)
// we can use record instead of a class for brevity
record Book(string Title, string Author)
Console.WriteLine("Enter title of the book");
var title = Console.ReadLine();
Console.WriteLine("Enter it's author");
var author = Console.ReadLine();
var book = new Book(title, author);

listOfBooks.Add(book);
Console.WriteLine("Enter title of the book");
var title = Console.ReadLine();
Console.WriteLine("Enter it's author");
var author = Console.ReadLine();
var book = new Book(title, author);

listOfBooks.Add(book);
Angius
Angiusā€¢10mo ago
Well, sure, you can zip them But the proper way to handle related data is... objects
SWR
SWRā€¢10mo ago
Just another way to do exactly what you asked for. But yes, do a structure if you can
Angius
Angiusā€¢10mo ago
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
Mysel
Myselā€¢10mo ago
omg thank you very much šŸ™
Pobiega
Pobiegaā€¢10mo ago
You can even put complex objects in other objects.
record Author(string Name, DateOnly DateOfBirth);
record Book(string Title, Author Author);
record Author(string Name, DateOnly DateOfBirth);
record Book(string Title, Author Author);
Accord
Accordā€¢10mo ago
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.