C
C#•2y 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•2y 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
MyselOP•2y ago
interesting i tried to make a class but i was struggling to get user input to add a book
Angius
Angius•2y 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•2y ago
Well, sure, you can zip them But the proper way to handle related data is... objects
SWR
SWR•2y ago
Just another way to do exactly what you asked for. But yes, do a structure if you can
Angius
Angius•2y 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
MyselOP•2y ago
omg thank you very much šŸ™
Pobiega
Pobiega•2y 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•2y 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.

Did you find this page helpful?