在C#中,可以使用LINQ(Language Integrated Query)擴(kuò)展方法對(duì)集合進(jìn)行排序。以下是一些常見(jiàn)排序方式的示例:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 4 };
// 使用OrderBy方法進(jìn)行升序排序
var sortedNumbers = numbers.OrderBy(n => n).ToList();
Console.WriteLine("升序排序:");
foreach (int number in sortedNumbers)
{
Console.Write(number + " ");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 4 };
// 使用OrderByDescending方法進(jìn)行降序排序
var sortedNumbers = numbers.OrderByDescending(n => n).ToList();
Console.WriteLine("降序排序:");
foreach (int number in sortedNumbers)
{
Console.Write(number + " ");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> words = new List<string> { "apple", "banana", "cherry", "date", "fig" };
// 使用OrderBy方法按字符串長(zhǎng)度排序
var sortedWords = words.OrderBy(s => s.Length).ToList();
Console.WriteLine("按長(zhǎng)度排序:");
foreach (string word in sortedWords)
{
Console.Write(word + " ");
}
}
}
這些示例展示了如何使用LINQ的OrderBy
和OrderByDescending
方法對(duì)集合進(jìn)行排序。你可以根據(jù)需要調(diào)整排序依據(jù)的表達(dá)式。