- Home /
Understanding Linq and orderbydescending
Hey everyone, was wondering if I could get some help.
I'm ordering a list of objects using Linq, which I'm pretty unfamiliar with but it's been going so okay so far. Well it was until I moved some script around.
myList = myList.OrderByDescending(x => x.GetComponent<CarCheckpoint>().currentprogress).ToList();
I was using the above line of code. I didn't entirely understand how it worked but I assumed that x was the value of the object in the list and by using a simple GetComponent I could grab the value I wanted the order the list by. It was working fine until I moved this script into a new file and attached it to a different object. Before it was part of the object's main script.
myList = myList.OrderByDescending(x => x.GetComponent<playerposition>().currentprogress).ToList();
So made some slight revisions to the code and this was result. But now it just throws u NullReference exception, so I assume it isn't successfully finding this value.
I've looked around the internet but would still like some light shed on a few things.
Does x represent the items in the list or the object it is attached to?
I am currently trying to grab an int from a script attached to an object inside the list, if the above code is incorrect how instead should I do this?
Sorry to be a pain guys, just this script is giving me a headache. Would really appreciate any clarity on this as the documentation is giving me a headache.
Thanks.
Answer by Matthew A · Mar 31, 2013 at 10:44 AM
x in the lambda expression is an item in the list (a GameObject from the looks of your code).
If you're getting a null reference exception, either your list is null, a GameObject in your list is null (may have been destroyed), or a GameObject doesn't have the correct component attached. You may have to refine your list to weed out possible problems:
GameObject[] allObjects = GameObject.FindGameObjectsWithTag("Foo"); // or however you're getting the original list...
var goodObjects = allObjects.Where(o => o != null && o.GetComponent() != null);
var result = goodObjects.OrderByDescending(o => o.GetComponent().progress);
Thanks so much for you help. So much more I need to learn! The issue was as you said. I hadn't attached the racer script to every object just 1. Lol late night program$$anonymous$$g ay? Thanks for your help.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
List/Array should handle another List/Array - Upgrade System - Performance 1 Answer
[Answered](C#)Comparing two Lists for a Crafting System 2 Answers
How do I compare two lists for equality (not caring about order) C# 6 Answers