Get the Nth Minimum or Nth Maximum number from a collection C#

For a collection of integers/decimals, we can use the .Max() and .Min() to get the maximum and minimum value of the collection respectively.
However, there are two more case scenarios, that I have faced, which I am going to discuss next. Following is the definition of a class Item that I am going to use here:

class Item: IComparable<Item>
{
    public string itemName { get; set; }
    public int itemPrice { get; set; }

    int IComparable<Item>.CompareTo(Item other)
    {
        if (other.itemPrice > this.itemPrice)
            return -1;
        else if (other.itemPrice == this.itemPrice)
            return 0;
        else 
            return 1;
    }

 
	//Operator overloading 

	public static bool operator >(Item X, Item Y)
	{
		if (X == null && Y == null)
		{
			return false;
		}
		if (X == null)
		{
			return false; //true?
		}
		if (Y == null)
		{
			return true; //false? 

		}

		return X.itemPrice > Y.itemPrice;
	}

	public static bool operator <(Item X, Item Y)
	{
		if (X == null && Y == null)
		{
			return false;
		}
		if (X == null)
		{
			return true; //false?
		}
		if (Y == null)
		{
			return false; //true? 

		}

		return X.itemPrice < Y.itemPrice;
	} 
}

 

Populate some value to the collection


Item[] items = { new Item { itemName="Item1", itemPrice=10 },
                 new Item { itemName="Item2", itemPrice=20 },
                 new Item { itemName="Item3", itemPrice=30 }, 
                 new Item { itemName="Item4", itemPrice=40 } };

Get the Minimum number greater than a certain value OR Maximum number lesser than a certain value


//get the minimum valued item = Item1
int min = items.Min().itemPrice;//get the min valued item greater than the 2nd item = Item3
int min = items.Where(p => p > items[1]).DefaultIfEmpty().Min().itemPrice);
//get the maximum valued item = Item4
int min = items.Max().itemPrice;

//get the max valued item less than the 3rd item = Item2
int min = items.Where(p => p < items[2]).DefaultIfEmpty().Max().itemPrice);

 

Similarly, we can also get the element at each index


Item secondLowest = numbers.OrderBy(num => num).ElementAt(1);
Item secondHighest = numbers.OrderBy(num => num).Reverse().ElementAt(1);

Advertisements

Determine the type of an Object in JavaScript

In javascript, all the variables are declared as var. However, sometimes we need to know the type of var to implement your logic. This is how you can determine some of the data types.

//chk if an object is an array or not.
function isArray(obj) {
//returns true is it is an array
    if (obj.constructor.toString().indexOf(“Array”) > -1){
        return true;
    }
    else{
        return false;
    }
}

To get the datatype, do the following:

var boolVal = true;
var numVal = 123;
var strVal = "String";
alert(typeof boolVal)    // displays "boolean"
alert(typeof numVal)     // displays "number"
alert(typeof strVal)     // displays "string"