gpt4 book ai didi

c# - 用于对不同属性中的不同对象进行排序的通用 IComparer

转载 作者:行者123 更新时间:2023-11-30 19:27:01 25 4
gpt4 key购买 nike

我正在尝试使用 IComparer 对对象数组进行排序。

我编写了代码,但它仅适用于特定对象。例如:

这门课

public class Cars
{
public string Name { get; set; }
public string Manufacturer { get; set; }
public int Year { get; set; }

public Cars(string name, string manufacturer, int year)
{
Name = name;
Manufacturer = manufacturer;
Year = year;
}
}

我的代码如下:

class MySort 
{
public class SortByYears : IComparer
{
int IComparer.Compare(Object x, Object y)
{
Cars X = (Cars)x, Y = (Cars)y;
return (X.Year.CompareTo(Y.Year));
}
}

public class SortByName : IComparer
{
int IComparer.Compare(Object x, object y)
{
Cars X = (Cars)x, Y = (Cars)y;
return (X.Name.CompareTo(Y.Name));
}
}

public class SortByManyfacturer : IComparer
{
int IComparer.Compare(object x, object y)
{
Cars X = (Cars)x, Y = (Cars)y;
return (X.Manufacturer.CompareTo(Y.Manufacturer));
}
}
}

但是如果我添加另一个具有不同属性的类,它将毫无用处。

那么是否有机会修改这段代码,使其适用于具有不同属性的对象?

最佳答案

class SortComparer<T> : IComparer<T>
{
private PropertyDescriptor PropDesc = null;
private ListSortDirection Direction =
ListSortDirection.Ascending;

public SortComparer(object item,string property,ListSortDirection direction)
{
PropDesc = TypeDescriptor.GetProperties(item)[property];
Direction = direction;
}

int IComparer<T>.Compare(T x, T y)
{
object xValue = PropDesc.GetValue(x);
object yValue = PropDesc.GetValue(y);
return CompareValues(xValue, yValue, Direction);
}

private int CompareValues(object xValue, object yValue,ListSortDirection direction)
{

int retValue = 0;
if (xValue is IComparable) // Can ask the x value
{
retValue = ((IComparable)xValue).CompareTo(yValue);
}
else if (yValue is IComparable) //Can ask the y value
{
retValue = ((IComparable)yValue).CompareTo(xValue);
}
// not comparable, compare String representations
else if (!xValue.Equals(yValue))
{
retValue = xValue.ToString().CompareTo(yValue.ToString());
}
if (direction == ListSortDirection.Ascending)
{
return retValue;
}
else
{
return retValue * -1;
}
}
}

调用代码:

假设一个名为 lst 的列表:

lst.Sort(new SortComparer<Cars>(lst[0],"YourPropertyName",ListSortDirection.Ascending));

关于c# - 用于对不同属性中的不同对象进行排序的通用 IComparer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074893/

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