.NET ヘルプ

C# Orderby(開発者向けの仕組み)

更新済み 2月 18, 2024
共有:

整列はどのプログラミング言語でも基本的な操作であり、C#のOrderByメソッドはコレクション内の要素を整理するための強力なツールです。 配列、リスト、その他の列挙可能な構造を扱う際に、OrderByを活用する方法を理解することで、コードの可読性と機能性が大幅に向上します。

この記事の後半では、 IronPDF 私たちがLINQのOrderByメソッドとIronPDFを使用してフォーマットされ並べ替えられたPDFを生成する方法。

LINQ OrderBy メソッドとは何ですか?

OrderBy メソッドは LINQ の一部です。 (言語統合クエリ (Language-Integrated Query)) C#でのライブラリであり、要素を昇順に並べ替えるために特別に設計されています。昇順での並べ替えはデフォルトの方法であるため、昇順のキーワードは必要ありません。

LINQ Orderby メソッドの使い方

データを昇順にソートする

C#でこのメソッドを適用する方法は2つあります。 メソッド構文またはクエリ構文を通じて。 方法の構文を使用します。これは簡単明瞭だからです。

var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
Dim sortedCollection = collection.OrderBy(Function(item) item.OrderByProperty)
VB   C#

ここで、コレクションはソートしたい IEnumerable ソースコレクションであり、OrderByProperty は要素を並べ替えたいプロパティや式です。 OrderBy 内のラムダ式拡張メソッドは、ソートの基準を指定します。

データを降順で並べ替える

降順で並べ替えるには、メソッドベースの構文を使用して OrderByDescending メソッドを使用できます。

var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);
var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);
Dim sortedCollectionDesc = collection.OrderByDescending(Function(item) item.OrderByProperty)
VB   C#

複数の基準によるデータの並べ替え

実際のシナリオでは、複数の条件に基づいてコレクションをソートする必要がよくあります。 OrderByは、複数のThenByまたはThenByDescending呼び出しをチェーンすることでこれを可能にします:

var multiSortedCollection = collection
    .OrderBy(item => item.OrderByProperty1)
    .ThenByDescending(item => item.OrderByProperty2);
var multiSortedCollection = collection
    .OrderBy(item => item.OrderByProperty1)
    .ThenByDescending(item => item.OrderByProperty2);
Dim multiSortedCollection = collection.OrderBy(Function(item) item.OrderByProperty1).ThenByDescending(Function(item) item.OrderByProperty2)
VB   C#

この例では、コレクションはまず昇順でOrderByProperty1によってソートされ、その後、同じOrderByProperty1の値を持つ要素については降順でOrderByProperty2によってソートされます。

カスタムコンパレータ

より複雑な並べ替えの要件には、カスタムコンパレータを使用できます。 OrderBy メソッドは、IComparer を渡すことを許可します次の例に示すように、実装を行います:

var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());
var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());
Dim customSortedCollection = collection.OrderBy(Function(item) item.Property, New CustomComparer())
VB   C#

以下は、CustomComparerIComparer を実装するクラスです。interface、要素を比較するためのカスタムロジックを提供します。

実用例:オブジェクトのソート

整数リストのソート

using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 2, 8, 1, 7 };
        var sortedNumbers = numbers.OrderBy(num => num);
        Console.WriteLine("Sorted Numbers:");
        foreach (var number in sortedNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 2, 8, 1, 7 };
        var sortedNumbers = numbers.OrderBy(num => num);
        Console.WriteLine("Sorted Numbers:");
        foreach (var number in sortedNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Program
	Shared Sub Main()
		Dim numbers As New List(Of Integer) From {5, 2, 8, 1, 7}
		Dim sortedNumbers = numbers.OrderBy(Function(num) num)
		Console.WriteLine("Sorted Numbers:")
		For Each number In sortedNumbers
			Console.WriteLine(number)
		Next number
	End Sub
End Class
VB   C#

この例では、整数のリストが OrderBy を使用して昇順にソートされます。

文字列のリストのソート

using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        List<string> names = new List<string> { "Alice", "Charlie", "Bob", "David" };
        var sortedNames = names.OrderBy(name => name);
        Console.WriteLine("Sorted Names:");
        foreach (var name in sortedNames)
        {
            Console.WriteLine(name);
        }
    }
}
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        List<string> names = new List<string> { "Alice", "Charlie", "Bob", "David" };
        var sortedNames = names.OrderBy(name => name);
        Console.WriteLine("Sorted Names:");
        foreach (var name in sortedNames)
        {
            Console.WriteLine(name);
        }
    }
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Program
	Shared Sub Main()
		Dim names As New List(Of String) From {"Alice", "Charlie", "Bob", "David"}
		Dim sortedNames = names.OrderBy(Function(name) name)
		Console.WriteLine("Sorted Names:")
		For Each name In sortedNames
			Console.WriteLine(name)
		Next name
	End Sub
End Class
VB   C#

この例は、文字列のリストをアルファベット順に昇順でソートする方法を示しています。

カスタムオブジェクトのリストをソートする

using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe", Age = 30 },
            new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
            new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
        };
        var sortedPeople = people.OrderBy(person => person.Age);
        Console.WriteLine("Sorted People by Age:");
        foreach (var person in sortedPeople)
        {
            Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");
        }
    }
}
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe", Age = 30 },
            new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
            new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
        };
        var sortedPeople = people.OrderBy(person => person.Age);
        Console.WriteLine("Sorted People by Age:");
        foreach (var person in sortedPeople)
        {
            Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");
        }
    }
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	Public Property Age() As Integer
End Class
Friend Class Program
	Shared Sub Main()
		Dim people As New List(Of Person) From {
			New Person With {
				.FirstName = "John",
				.LastName = "Doe",
				.Age = 30
			},
			New Person With {
				.FirstName = "Alice",
				.LastName = "Smith",
				.Age = 25
			},
			New Person With {
				.FirstName = "Bob",
				.LastName = "Johnson",
				.Age = 35
			}
		}
		Dim sortedPeople = people.OrderBy(Function(person) person.Age)
		Console.WriteLine("Sorted People by Age:")
		For Each person In sortedPeople
			Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}")
		Next person
	End Sub
End Class
VB   C#

この例では、カスタムなPersonオブジェクトのリストが年齢プロパティに基づいて昇順にソートされます。

以下の出力がコンソールに表示されます。

C# Orderby(開発者向けのしくみ):図1 - カスタムオブジェクトをソートする前述のコードの出力

文字列の比較の取り扱い

文字列プロパティを扱う場合、大文字小文字を区別しないソートを保証したいかもしれません:

var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);
var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);
Dim sortedPeopleByName = people.OrderBy(Function(person) person.LastName, StringComparer.OrdinalIgnoreCase)
VB   C#

この例では、StringComparer.OrdinalIgnoreCase を使用して、LastName プロパティに基づく大文字と小文字を区別しないソートを実行します。

パフォーマンスに関する考慮事項

LINQはコレクションを整理するための簡潔な方法を提供しますが、特に大規模なデータセットの場合にはパフォーマンスの影響を考慮することが重要です。 パフォーマンスが重要なシナリオでは、Listを使用してその場でソートするような代替案を検討することをお勧めします。.Sort` メソッド。

IronPDFの紹介

IronPDF は、からのC# PDFライブラリです アイアンソフトウェア PDFドキュメントの読み取りと生成をサポートします。 それは、スタイル情報を持つフォーマット済みのドキュメントを簡単にPDFに変換できます。 IronPDFは、HTML文字列から簡単にPDFを生成することができます。また、URLからHTMLをダウンロードしてからPDFを生成することもできます。

インストール

IronPDFは以下を使用してインストールできます NuGet パッケージマネージャーコンソールまたはVisual Studioパッケージマネージャーを使用します。

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

NuGetパッケージマネージャーの検索バーに「ironpdf」と入力して検索することで、IronPDFをインストールすることもできます。

C# Orderby(開発者向けの使い方): 図 2 - NuGet パッケージ マネージャーを通じて IronPDF をインストールする

IronPDFを使用してPDFを生成する

以下は、HTML文字列とIronPDFジェネレーターを使用してPDFレポートを生成するためのコードです。

// See https://aka.ms/new-console-template for more information
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe", Age = 30 },
            new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
            new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
        };
        var sortedPeople = people.OrderBy(person => person.Age);
        string name = "Sam";
        var count = people.Count;
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" +
string.Join("\n", sortedPeople.Select(person => $"{person.FirstName} {person.LastName}, Age: {person.Age}"))
+ @"
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
    }
}
// See https://aka.ms/new-console-template for more information
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe", Age = 30 },
            new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
            new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
        };
        var sortedPeople = people.OrderBy(person => person.Age);
        string name = "Sam";
        var count = people.Count;
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" +
string.Join("\n", sortedPeople.Select(person => $"{person.FirstName} {person.LastName}, Age: {person.Age}"))
+ @"
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
    }
}
Imports Microsoft.VisualBasic

' See https://aka.ms/new-console-template for more information
Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	Public Property Age() As Integer
End Class
Friend Class Program
	Shared Sub Main()
		Dim people As New List(Of Person) From {
			New Person With {
				.FirstName = "John",
				.LastName = "Doe",
				.Age = 30
			},
			New Person With {
				.FirstName = "Alice",
				.LastName = "Smith",
				.Age = 25
			},
			New Person With {
				.FirstName = "Bob",
				.LastName = "Johnson",
				.Age = 35
			}
		}
		Dim sortedPeople = people.OrderBy(Function(person) person.Age)
		Dim name As String = "Sam"
		Dim count = people.Count
		Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" & String.Join(vbLf, sortedPeople.Select(Function(person) $"{person.FirstName} {person.LastName}, Age: {person.Age}")) & "
</body>
</html>"
' Create a new PDF document
		Dim pdfDocument = New ChromePdfRenderer()
		pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf")
	End Sub
End Class
VB   C#

ここでは、レポートに必要なすべての書式を含む昇順で並べ替えられた sortedPeople からHTML文字列を最初に生成しています。 次にIronPDFを使用してPDF文書を生成します。 RenderHtmlAsPdf メソッドを使用してHTML文字列をPDFドキュメントに変換します。

出力

以下の出力はPDFで利用可能です。

C# Orderby(開発者のための動作方法):図3 - 前述のコードから出力されたPDF

ライセンス(無料トライアル利用可能)

試用キーはから取得できます これ. このキーはappsettings.jsonに配置する必要があります。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

試用ライセンスを取得するためにメールアドレスを提供してください。

結論

C#のOrderByメソッドは、さまざまな基準に基づいてコレクションをソートするための多用途なツールです。 昇順または降順での並べ替え、単一または複数の基準による並べ替え、またはカスタムコンパレータの使用に関わらず、OrderByを習得することは、コードの明確さと効率を大幅に向上させることができます。

一緒に IronPDF、これは、ドキュメントとして美しくフォーマットされ、整列されたコレクションを生成するための素晴らしい組み合わせです。

< 以前
C# Dev Kit VS Code 拡張機能(開発者向けの動作方法)
次へ >
MSTest C# (開発者向けの動作説明)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >