.NET ヘルプ

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

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

この記事の後半では、Iron Software の IronPDF ライブラリと LINQ の OrderBy メソッドおよび IronPDF を使用してフォーマットおよびソートされたPDFを生成する方法を紹介します。

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

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

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)
$vbLabelText   $csharpLabel

ここで、コレクションはソートしたい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)
$vbLabelText   $csharpLabel

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

実際のシナリオでは、複数の条件に基づいてコレクションをソートする必要がよくあります。 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)
$vbLabelText   $csharpLabel

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

カスタムコンパレータ

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

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())
$vbLabelText   $csharpLabel

ここで、CustomComparerIComparer<T>インターフェースを実装するクラスで、要素を比較するためのカスタムロジックを提供します。

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

整数のリストの並べ替え

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
$vbLabelText   $csharpLabel

この例では、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
$vbLabelText   $csharpLabel

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

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

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
$vbLabelText   $csharpLabel

この例では、カスタムな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)
$vbLabelText   $csharpLabel

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

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

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

IronPDFの紹介

IronPDFの機能を発見し、Iron SoftwareのC# PDFライブラリ内でPDFドキュメントの読み取りと生成をサポートします。 スタイル情報を含むフォーマット文書を簡単にPDFに変換できます。 IronPDFはHTML文字列からPDFを生成することもできますし、URLからHTMLをダウンロードしてPDFを生成することもできます。

IronPDFは、HTMLをPDFに変換する際に、そのすべてのレイアウトとスタイルを保持することで優れています。 それは、レポート、請求書、文書などのさまざまなウェブコンテンツからPDFを生成することができます。 このツールは、HTMLファイル、URL、およびHTML文字列を使用してPDFファイルを作成します。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

インストール

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
$vbLabelText   $csharpLabel

検索バーで "ironpdf "を検索し、NuGetパッケージマネージャを使って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
$vbLabelText   $csharpLabel

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

出力

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

C# Orderby(開発者向けの仕組み):図3 - 前のコードから出力されたPDF

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

試用キーはIronPDF Trial Licenseから取得できます。 このキーは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"
$vbLabelText   $csharpLabel

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

結論

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

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

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
C# Dev Kit VS Code 拡張機能(開発者向けの動作方法)
次へ >
MSTest C# (開発者向けの動作説明)