C# List 元素(Object)排序

C# List 元素(Object)排序

C# List<T> 元素(Object)排序


資料來源: https://www.delftstack.com/zh-tw/howto/csharp/sort-list-by-field-in-csharp/

線上編譯器: https://dotnetfiddle.net/


Code

using System;
using System.Linq;
using System.Collections.Generic;
 
public class PersonData
{
    public string name;

 
    public PersonData(string name)
    {
        this.name = name;
   
    }
 
    public override string ToString() {
        return name;
    }
}
 
public class SortList
{
    public static void Main()
    {
        PersonData tom = new PersonData("Tom");
        PersonData roger = new PersonData("Roger");
        PersonData fred = new PersonData("Fred");
        PersonData jack = new PersonData("Jack");
        PersonData anna = new PersonData("Anna");

 
        List<PersonData> mergedList = new List<PersonData>() { tom, roger, fred, jack, anna };
 
        mergedList.Sort((x, y) => {
                        int ret = String.Compare(x.name, y.name);
                        return ret;
                    });
 
        Console.WriteLine(String.Join(Environment.NewLine, mergedList));
    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *