c#

c# compareto 能否进行部分排序

小樊
81
2024-11-16 12:46:38
栏目: 编程语言

在C#中,CompareTo方法通常用于比较两个对象的值。如果你想要对对象的部分属性进行排序,你可以使用LINQ(Language Integrated Query)来实现。

假设你有一个名为Person的类,其中包含FirstNameLastName属性:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

你可以使用LINQ的OrderByThenBy方法对Person对象的集合进行部分排序:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe" },
            new Person { FirstName = "Jane", LastName = "Doe" },
            new Person { FirstName = "John", LastName = "Smith" },
            new Person { FirstName = "Jane", LastName = "Smith" }
        };

        var sortedByName = people.OrderBy(p => p.FirstName).ThenBy(p => p.LastName);
        var sortedByLastName = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName);

        Console.WriteLine("Sorted by First Name, then Last Name:");
        foreach (var person in sortedByName)
        {
            Console.WriteLine($"{person.FirstName} {person.LastName}");
        }

        Console.WriteLine("\nSorted by Last Name, then First Name:");
        foreach (var person in sortedByLastName)
        {
            Console.WriteLine($"{person.FirstName} {person.LastName}");
        }
    }
}

在这个例子中,我们首先按照FirstNamePerson对象进行排序,然后按照LastName进行排序。这样,你可以根据需要对对象的属性进行部分排序。

0
看了该问题的人还看了