C# 使用CompareTo对具有两个参数的列表进行排序
我目前正在使用列表中包含的对象类型中的“CompareTo”方法对C#list进行排序。我想按WBS(工作分解结构)对所有项目进行升序排序,我可以使用以下代码很好地管理这些项目:C# 使用CompareTo对具有两个参数的列表进行排序,c#,list,sorting,compareto,C#,List,Sorting,Compareto,我目前正在使用列表中包含的对象类型中的“CompareTo”方法对C#list进行排序。我想按WBS(工作分解结构)对所有项目进行升序排序,我可以使用以下代码很好地管理这些项目: public int CompareTo(DisplayItemsEntity other) { string[] instanceWbsArray = this.WBS.Split('.'); string[] otherWbsArray
public int CompareTo(DisplayItemsEntity other)
{
string[] instanceWbsArray = this.WBS.Split('.');
string[] otherWbsArray = other.WBS.Split('.');
int result = 0;
for (int i = 0; i < maxLenght; i++)
{
if (instanceWbsArray[i].Equals(otherWbsArray[i]))
{
continue;
}
else
{
result = Int32.Parse(instanceWbsArray[i]).CompareTo(Int32.Parse(otherWbsArray[i]));
break;
}
}
return result;
}
public int CompareTo(DisplayItemsEntity其他)
{
字符串[]instanceWbsArray=this.WBS.Split('.');
字符串[]otherWbsArray=other.WBS.Split('.');
int结果=0;
对于(int i=0;i
现在,在考虑第二个参数(WBS)之前,我希望能够考虑多个参数进行排序,如按字母顺序排列的项目名称。我怎样才能做到这一点?我不知道您的类的详细信息,因此我将提供一个使用字符串和LINQ列表的示例
OrderBy
将按字母顺序对字符串排序,然后再按长度排序。您可以很容易地根据需要调整此示例
var list = new List<string>
{
"Foo",
"Bar",
"Foobar"
};
var sortedList = list.OrderBy(i => i).
ThenBy(i => i.Length).
ToList();
var list=新列表
{
“福”,
“酒吧”,
“Foobar”
};
var sortedList=list.OrderBy(i=>i)。
然后是(i=>i.Length)。
托利斯特();
首先按字母顺序比较项目名称,如果它们不等于返回值,则根据第二个值执行比较
public int CompareTo(DisplayItemsEntity other)
{
if(other.ProjectName.CompareTo(this.ProjectName) != 0)
{
return other.ProjectName.CompareTo(this.ProjectName)
}
//else do the second comparison and return
return result;
}
在像您这样的案例中,我们通常会这样做:
public int CompareTo( SomeClass other )
{
int result = this.SomeProperty.CompareTo( other.SomeProperty );
if( result != 0 )
return result;
result = this.AnotherProperty.CompareTo( other.AnotherProperty );
if( result != 0 )
return result;
[...]
return result;
}
附言。
发布代码时,请尽量只包含与您的问题相关的代码。您发布的代码中有大量我不需要阅读的内容,这实际上让我的眼睛很痛。我喜欢Eve的答案,因为它很灵活,但我有点惊讶,没有人提到创建自定义实例
IComparer
是一个通用接口,它定义了比较类型T
的两个实例的方法。使用IComparer
的优点是,您可以为常用的每个排序顺序创建实现,然后在必要时使用这些实现。这允许您在typesCompareTo()
方法中创建默认排序顺序,并单独定义替代顺序
例如
公共类MyComparer
:I比较
{
公共整数比较(YourType x,YourType y)
{
//在这里添加比较逻辑
}
}
IComparer
对于组合特别有用,您可以使用一个比较器,使用另一个对属性类型进行操作的比较器来比较给定类型的某些属性
如果需要对不受控制的类型定义排序,它也非常有用。它的另一个优点是不需要LINQ,因此可以在较旧的代码(.Net 2.0以后)中使用。如何使用“OrderBy()”方法?@JFB假设您使用的是.Net 3.5或更高版本,则需要在文件的using
指令中包括:using System.LINQ代码>哎呀!现在我很尴尬。谢谢
public class MyComparer
: IComparer<YourType>
{
public int Compare(YourType x, YourType y)
{
//Add your comparison logic here
}
}