Home > database >  c# How to find max value in an array containing objects
c# How to find max value in an array containing objects

Time:01-15

I am new to programming and have come to a point in my app where I am really stuck. I am familiar on how to handle arrays containing single values and bubble sort, but now I am working with an array containing objects from a separate class and want to find the highest value from a private variable in all the objects and print out that object to the user. The array is empty at first and the user is to fill the array with data. This is the class:

class SoldItem
    {
        private int uniqueId;
        private string itemName;
        private string artist;
        private string itemType;
        private decimal finalPrice;
        private decimal listingPrice;
        private int bidders;

        //Constructor
        public SoldItem(int uniqueId,
            string itemName,
            string artist,
            string itemType,
            decimal finalPrice,
            decimal listingPrice,
            int bidders)
        {
            this.uniqueId = uniqueId;
            this.itemName = itemName;
            this.artist = artist;
            this.itemType = itemType;
            this.finalPrice = finalPrice;
            this.listingPrice = listingPrice;
            this.bidders = bidders;
        }

        //Convert to string method
        public override string ToString()
        {
            return "Unique id: "   uniqueId  
                "\nItem name: "   itemName  
                "\nBy: "   artist  
                "\nType: "   itemType  
                "\nSold for: "   finalPrice  
                "\nAsking price: "   listingPrice  
                "\nBidders: "   bidders;
        }

        //Public method to access final price from other classes
        public decimal GetFinalPrice()
        {
            return finalPrice;
        }

    }

The variable I want to fint the highest value from is finalPrice, any ideas on how to go about this? Thanks in advance.

CodePudding user response:

Use Linq.

var soldItem = soldItems.MaxBy(soldItem => soldItem.GetFinalPrice());

CodePudding user response:

SoldItem corvette67 = new SoldItem(/*initialize*/);
SoldItem amDB4 = new SoldItem(/*initialize*/);
........
........
.......
DoBubbleSort(corvette67.GetFinalPrice(), amDB4.GetFinalPrice())
{
    // sorting logic
}

To access an instance variable you can use the objects(corvette67 and amDB4 in this case) of that class. corvette67 and amDB4 are our objects to access SoldItem class variables that are non-static. If it is a static type you want to access, it can be done by using Class name. ex: SoldItem.SomeStaticMethod()

  •  Tags:  
  • Related