gpt4 book ai didi

c# - 在没有 LINQ 或委托(delegate)的情况下对 C# List<> 进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:21 24 4
gpt4 key购买 nike

我有一个对象列表,每个对象在 3D 空间中都有一个位置。我需要按到任意点的距离对这个列表进行排序。目前我正在这样做:

_attachedEffectors = _attachedEffectors.OrderBy(x =>
Mathf.Pow((x.transform.position.x - position.x), 2) + Mathf.Pow((x.transform.position.y - position.y), 2) + Mathf.Pow((x.transform.position.z - position.z), 2)
).ToList();

但是,不幸的是,我受制于使用 Unity 的编译器,该编译器在内存分配和 LINQ/委托(delegate)方面非常糟糕。有没有办法在不使用 LINQ 或委托(delegate)的情况下对这样的列表进行排序?最好是分配很少或不分配内存的搜索,因为我需要在一帧中多次运行这个东西。

此外,将来可能还会有其他任意的搜索限制(例如,如果与该特定对象的距离大于某个对象特定的最大距离,则忽略它)

编辑:我认为我没有清楚地解释我的问题。我知道排序算法,但是,所有这些解决方案都与 2 个独立可比较的对象有关。我在问如何根据外部变量对这些对象进行排序。也就是说,它们需要根据到空间中给定点的距离进行排序,对象知道,但排序算法知道。我知道这可以通过了解这一点的对象来完成,但这对我来说是糟糕的设计。

基本上,我需要一个 Sort() 实现,它接受一个参数以及要排序的对象,并将该参数与对象结合使用以对列表进行排序(如 LINQ 实现中所示 - 位置是参数此行所在的函数)。

最佳答案

您可以使用 List.Sort()。但是,如果您想使用此方法,存储在列表中的对象类型应实现 IComparable 接口(interface)。下面我提供了一个代码示例,您可以基于该示例编写自己的代码:

public class Customer : IComparable<Customer>
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public Customer(int age, string firstName, string lastName)
{
Age = age;
FirstName = firstName;
LastName = lastName;
}

public int CompareTo(Customer other)
{
return Age.CompareTo(other.Age);
}
}

class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>
{
new Customer(25,"a","b"),
new Customer(21,"c","d"),
new Customer(22,"e","f"),
new Customer(28,"g","i"),
new Customer(30,"j","k"),
new Customer(23,"l","m"),
new Customer(31,"a","b"),
};


customers.Sort();

foreach (var customer in customers)
{
Console.WriteLine(customer.Age);
}

Console.ReadKey();
}
}

关于 List.Sort() 方法的复杂性,如 MSDN 中所述,

On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n ^ 2) operation.

关于c# - 在没有 LINQ 或委托(delegate)的情况下对 C# List<> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com