使用Comparer通过不同的字段对C#中的IEnumerable进行排序

use*_*322 8 c# linq icomparer

我有一个对象列表,需要根据对象的三个不同属性进行排序.例

CLass Object1{ Property1 , Property2, Property3}

ListObj = IEnumerable<Object1>

Foreach ( item in ListObj){

    if (item.Property1 == true)
       item goes at top of list
    if(item.Property2 == true)
       item goes end of list
    if(item.Property3 == true)
        item can go anywhere.
}
Run Code Online (Sandbox Code Playgroud)

结束列表应该是Property1 = true的对象,后跟Property2 = true的对象,后跟Property3 = true的对象

Dav*_*ton 8

为什么不使用LINQ?

var orderedList = 
   ListObj.OrderByDescending(x => x.Property1)
          .ThenByDescending(x => x.Property2);
Run Code Online (Sandbox Code Playgroud)


Mar*_*ann 5

您自己的标题已经说明了一切:实现自定义IComparer<Object1>并将其传递给OrderBy扩展方法:

var orderedItems = ListObj.OrderBy(obj => obj, customComparer);
Run Code Online (Sandbox Code Playgroud)