0

I am using adding two variables in my SetValues list. The variables are Position and Value. Now I want to check in my List what is the maximum Value and what is the minimum Value (For only "Value"). Now when I do the following:

[Serializable]
    public struct SetValues {
        public float Position;
        public float Value;
    }

    public List<SetValues> setValues;

void Start () {
        Debug.Log (setValues.Value.Min ());
    }

It says that "does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type could be found". The only reason I want to use List is to avoid iteration that should be done when using an array. But what is the mistake am I doing here?

Naik
  • 83
  • 8
  • 3
    `var min = setValues.Min(z => z.Value);` – mjwills Feb 17 '21 at 13:18
  • 3
    *"to avoid iteration that should be done when using an array"* - you can't avoid iterations to find min, unless collection is sorted. [Related](https://stackoverflow.com/q/434761/1997232). – Sinatr Feb 17 '21 at 13:21

1 Answers1

2

You have at your disposition the IEnumerable extensions provided in the Linq namespace. It is just a simple line of code for min and another one for max

var minV = setValues.Min(x => x.Value);
var maxV = setValues.Max(x => x.Value);

However, you cannot avoid an iteration over the list. The Min and Max extensions contains an hidden loop that seeks the value requested.

Your code cannot work because setValues is a list of SetValues objects. It is confusing for us with just a letter different by its case but it is a clear error for the compiler that complains about it. I suggest to find a different name for the class or a different name for the list variable

Steve
  • 213,761
  • 22
  • 232
  • 286