gpt4 book ai didi

c# - LINQ 如何根据给定条件对项目进行排序?

转载 作者:太空狗 更新时间:2023-10-30 00:20:45 31 4
gpt4 key购买 nike

假设我们有一个 MyData实现 IComparable<MyData> 的类和 IComparable接口(interface)。然后我们有一个包含许多 MyData 的列表元素和 LINQ 查询以获取排序列表。

public class MyData : IComparable<MyData>, IComparable
{
...

public int CompareTo(MyData value)
{
// TODO
}

public int CompareTo(object value)
{
if (value == null)
return 1;

if (value.GetType() == typeof(MyData))
{
MyData rightValue = (MyData)value;
return (this.CompareTo(rightValue));
}
else throw new ArgumentException("Object is not a " + typeof(MyData) + ".");
}
}

// main method
List<MyData> list = new List<MyData>();
...
var items = from item in list
orderby item descending
select item;

当 LINQ 对 list 中的元素进行排序时, 它是否使用了 IComparable 的实现MyData 中的界面类(class)?

如果答案是,是否将排序标准封装在类MyData 中更好? (通过实现上述接口(interface))或在 LINQ 查询中指定条件(没有实现这些接口(interface)的 MyData)?这两种选择的优缺点是什么?

最佳答案

Enumerable.OrderBy “通过使用默认比较器 Default 来比较键”,这反过来将使用您的 IComparable<T>实现。

If the answer is yes, is it better to encapsulate the sort criteria in the class MyData (by implementing the above interfaces) or specify the criteria in a LINQ query (without MyData that implements these interfaces)? What are the pros and cons of these two choices?

所以首先,答案是肯定的。

这两种方法各有优势。

实现 IComparable<T>表明该类型具有自然顺序。当这是真的时,我喜欢实现这个接口(interface)。就 LINQ 而言,主要优点是您可以(稍微)简化 LINQ 查询。然而,我的主要建议是针对给定类型的“自然”顺序的建议,这反过来又增加了 API 的清晰度。

在 LINQ 查询本身中指定条件的主要优点是灵 active 。这允许您按任意数量的标准进行排序 - 而不是将自己限制在类型本身中定义的给定排序。如果该类型没有“自然”排序顺序(即:它不代表某种完全独立或类似的“数量”),那么我个人会使用这种方法。

关于c# - LINQ 如何根据给定条件对项目进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9283622/

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