Unity课程中C#匿名函数排序逻辑疑问:actionValue减法实现排序的原理解析
Great question! Let's break down exactly how that anonymous function is sorting your EnemyAIAction list by actionValue—it's all about how C#'s List.Sort() method uses comparison delegates.
How List.Sort() Uses the Comparison Delegate
First, let's recap the core rule that List.Sort() follows when you pass it a comparison function (like your anonymous lambda):
- If the function returns a negative number, the first parameter (
a) should come before the second parameter (b) in the sorted list. - If the function returns 0, the order of
aandbdoesn't matter (they're considered equal for sorting purposes). - If the function returns a positive number, the second parameter (
b) should come before the first parameter (a) in the sorted list.
Breaking Down Your Anonymous Function
Your sorting line looks like this:
enemyAIActionList.Sort( (EnemyAIAction a, EnemyAIAction b) => b.actionValue - a.actionValue );
Let's translate this into plain language with concrete numbers to make it clear:
Suppose we have two EnemyAIAction instances:
ahas anactionValueof 5bhas anactionValueof 10
When we calculate b.actionValue - a.actionValue, we get 10 - 5 = 5 (a positive number). Following the Sort() rules, this tells the method to place b before a—so the higher value comes first.
Another example:
ahas anactionValueof 8bhas anactionValueof 3
Here, 3 - 8 = -5 (a negative number). This tells Sort() to place a before b—keeping the higher value first.
If both values are equal (e.g., a.actionValue = 6, b.actionValue = 6), the result is 0, so their relative order stays as-is.
Putting this all together, your lambda function sorts the list in descending order of actionValue—highest values at the top of the list, lowest at the bottom.
Why This Works for Your Enemy AI Use Case
Since you're trying to find the best enemy AI action, sorting by actionValue in descending order makes perfect sense: the first item in the sorted list will be the action with the highest value (your "best" action). I assume your method will end with something like return enemyAIActionList[0]; to grab that top result!
内容的提问来源于stack exchange,提问作者James MacDonald

