Search Unity

Min and Max in a generic list?

Discussion in 'Scripting' started by Nanako, Feb 1, 2016.

  1. Nanako

    Nanako

    Joined:
    Sep 24, 2014
    Posts:
    1,047
    I can't seem to figure out how to get this working

    I'd usually use Mathf.Min(myArray) to find the lowest value in an array, but right now i need to use a generic list of floats instead

    Mathf.Min doesn't take generic lists as input.
    I was hoping there might be a MyList.Min property, but it doesn't seem so.

    With a bit of googling, i found this function: https://msdn.microsoft.com/library/bb919785(v=vs.90).aspx

    It looks like what i need, but i can't for the life of me figure out how to use it. Can someone give me a syntax example of how to use that, assuming my list is declared as so. and then has values added to it:
    Code (CSharp):
    1. List<float> myList = new List<float>();
     
  2. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    779
    Assuming the list isn't too big, just call ToArray() and then use your normal min/max call.
     
  3. ensiferum888

    ensiferum888

    Joined:
    May 11, 2013
    Posts:
    265
    List.Min() returns an instance of the minimum element in the list.

    So from what I understand you could just do the following:
    Code (CSharp):
    1. float myMin = myList.Min();
    2. Debug.Log(myMin);
    Not tested in unity, as per the documentation this is a .Net 3.5 feature if I recall correctly Unity uses an older version but don't quote me on that I might be wrong.
     
  4. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    779
    You need using System.Linq for this to work.
     
    chainalonez and Nanako like this.
  5. Nanako

    Nanako

    Joined:
    Sep 24, 2014
    Posts:
    1,047
    Ding! we have a winner. this is what i was missing, thank you <3