如何排序列表?

时间:2014-06-05 14:44:55

标签: c# .net linq sorting

如何通过其MemberRole排序下面的客户列表,例如Golden先是Silver,其余的是他们的Firstname&姓氏。

public class  Customer
{
    public string id { get; set; }
    public string Firstname { get; set; } 
    public string Lastname { get; set; }
    public string memberRole { get; set; } // Golden and Silver 
}

List<Customer> customers = new List<Customer>();

4 个答案:

答案 0 :(得分:1)

OrderByDescending可以使用true 而不是false的布尔值:

customers  = customers 
    .OrderByDescending(c => c.memberRole == "Golden")
    .ThenBy(c => c.Firstname)
    .ThenBy(c => c.LastName)
    .ToList();

答案 1 :(得分:1)

customers.OrderBy(c => 
   c.memberRole == "Golden" ? 0 : (c.memberRole == "Silver" ? 1 : 2))
 .ThenBy(c => c.FirstName)
 .ThenBy(c => c.LastName)

答案 2 :(得分:1)

从设计的角度来看,最好将成员角色比较放入单独的类中。这样,如果出现新角色,您可以轻松地重复使用它,进行单元测试和升级。对于LINQ兼容性,最好实现IComparer类。

public class MemberRoleComparison : IComparer<string>
{
    // Put in required order from most importan to less
    internal static readonly string[] ROLES = { "Golden", "Silver", "Bronze" };

    int IComparer<string>.Compare(string x, string y)
    {
        return Array.IndexOf(ROLES, x).CompareTo(Array.IndexOf(ROLES, y));
    }
}

然后排序看起来像:

var sorted = customers
    .OrderBy(item => item.memberRole, new MemberRoleComparison())
    .ThenBy(c => c.Firstname)
    .ThenBy(c => c.Lastname)
;

如果可以通过规范,您可能希望用枚举替换角色的字符串表示。

public enum MemberRole
{
    Golden = 1,
    Silver = 2,
    Bronze = 3
}

然后,您可以直接比较角色,例如&#34; customer1.memberRole&gt; customer2.memberRole&#34;

如果要优化速度和内存消耗(通常快30-40%),最好使用List.Sort例程。首先定义客户比较可重用类:

public class CustomerComparison : IComparer<Customer>
{
    private IComparer<string> _RoleComparer = new MemberRoleComparison();

    int IComparer<Customer>.Compare(Customer x, Customer y)
    {
        int result = _RoleComparer.Compare(x.memberRole, y.memberRole);
        result = result == 0 ? string.Compare(x.Firstname, y.Firstname) : result;
        return result == 0 ? string.Compare(x.Lastname, y.Lastname) : result;
    }
}

然后只使用现有列表的Sort方法:

customers.Sort(new CustomerComparison());

但是为了获得更好的性能,您可能希望使用并行化的LINQ:

var sorted = customers
    .AsParallel()
    .OrderBy(item => item.memberRole, new MemberRoleComparison())
    .ThenBy(c => c.Firstname)
    .ThenBy(c => c.Lastname)
;

答案 3 :(得分:-1)

var result = customers
    .Select(z => new
        {
            OrderableRole = role == "Golden"
                ? 1
                : role == "Silver"
                    ? 2
                    : int.MaxValue,
            Customer = z
        })
    .OrderBy(z => z.OrderableRole)
    .ThenBy(z => z.Customer.Firstname)
    .ThenBy(z => z.Customer.LastName)
    .ToList();