Hi, I am trying to sort a list of objects, unit, by thier y position but am having difficulty using the C# list method of OrderByDescending. This is an example of it I found. Code (csharp): List<GameObject> sortedbydist = listofguys.OrderByDescending(x => x.Value).Select(p => p.Key).ToList(); I am unsure how to apply this to an existing list of class unit, accessing the transform of each, y position.
Thanks KesloMRK, quick question tho, clearly this logic (what I have) will not work. It is not incorporating each unit of the list. Code (csharp): list_unitsYPos_order = answerUnits.OrderByDescending(answerUnits => answerUnits.transform.position.y); Where answerUnits = list of count x.
That's saying that you're using the same name "answerUnits" as a variable name and a lambda variable name. Change it to something like: Code (csharp): list_unitsYPos_order = answerUnits.OrderByDescending(au => au.transform.position.y);
Ok, so essentially, this method(), tho I think technically may be an extension.... it is running thru all in the list answerUnits. But, I have a couple of questions, au, this is what? Obviously it needs to equate to an answerUnits. But where I am confused is, since this is not runnig thru a for(), how is the method gathering each answerUnits? PS. I have not tested, as I was leaving. Will test. Thanks!
Well, I would suggest reading about LINQ ( https://msdn.microsoft.com/en-us/library/bb397933.aspx ) and Lambda Expressions ( https://msdn.microsoft.com/en-us/library/bb397687.aspx ). Basically LINQ methods, like OrderByDescending, operate on lists (any IEnumerable actually) and return searched/reordered/transformed versions. Lambda expressions are of the form "x => DoSomething(x)" and translate to "given a variable x, do this to it". It's like a mini function where the parameter names are on the left side and the function body is on the right side. There's more to it than that but those are the basics.
Yes, the variable name on the left side of the lambda "=>" is sort of auto-declared, and it figures out what type it is by the statement that it's in; in your case the type is "GameObject", which it knows because you are calling OrderByDescending on a list of GameObjects.
To make it more clear, when you call someList.OrderByDescending(thing => thing.someNumber), it is saying "go through someList, and for each element, which we'll call "thing", get thing.someNumber, and use that value to decide what order to put the list in".
Right, I get that. However, I am still struggling with the logistics..... Code (csharp): list_unitsYPos_order = answerUnits.OrderByDescending(au => au.transform.position.y); edit, just so you know, answerUnits is a list of Answer_Unit class. list_unitsYPos is an empty list of float class.
Ah, but I am getting another error. First, it mentioned that I can not convert a float to a someClass. So I changed the class of the secondary list, from float, to someClass, but still an error.