In my class (Book) there is a variable (Bcopies) which indicates how many of these objects are “borrowed”
From my list (values) I already got the highest int which is to be displayed as the “most popular item”
I would like a better way to display that instead of multiple if statements for each instance of the variable in question(Bcopies) I thought of a foreach loop but don’t know how to implement with a variable inside a list
here is my program
namespace Library
{
class Program
{
static void Main(string[] args)
{
Book book1 = new Book("book one", "Author one", 900, 35, 16);
Book book2 = new Book("book two", "Author two", 240, 42, 8);
Book book3 = new Book("book three", "Author three", 700, 23, 8);
List<Book> BLibShelf = new List<Book>();
BLibShelf.AddRange(new List<Book>() { book1, book2, book3, book4, book5, book6, book7, book8 });
var values = new List<int> { book1.BCopies, book2.BCopies, book3.BCopies, book4.BCopies, book5.BCopies, book6.BCopies, book7.BCopies, book8.BCopies };
var t = values.Max();
//if statements allocating the "most popular"
if (book1.BCopies == t)
{
Console.WriteLine(book1);
}
if (book2.BCopies == t)
{
Console.WriteLine(book2);
}
if (book3.BCopies == t)
{
Console.WriteLine(book3);
}
here is my class
class Book
{
public string title;
public string author;
public int pages;
public int Libcopies;
public int BCopies;
public Book(string nTitle, string nAuthor, int nPages, int nLcopies, int nBcopies)
{
title = nTitle;
author = nAuthor;
pages = nPages;
Libcopies = nLcopies;
BCopies = nBcopies;
}
public override string ToString()
{
return "Book Title:" + title + " |Author:" + author + " |Pages:" + pages + " |Library Copies:" + Libcopies + " |Borrowed Copies:" + BCopies;
}
public int TotalCopy()
{
return BCopies + BCopies;
}
}
>Solution :
You are looking for ArgMax – argument (book in your case) on which we have Max value (BCopies).
You can do it with a help of Linq either via MaxBy (wants .Net 6+) or Aggregate (lower .Net versions):
using System.Linq;
...
Book mostPopular = BLibShelf
.Aggregate((most, book) => most.BCopies > book.BCopies ? most : book);
Console.Write($"The most popular book is {mostPopular}");