C# Distinctメソッドの使い方:重複を削除する方法
C#では、LINQ(Language Integrated Query)のDistinctメソッドを使用して、コレクションからユニークな要素を取得することができます。Distinctメソッドはコレクションから重複する要素を削除し、各要素の固有のインスタンスを保持します。
Distinctメソッドを使用する方法を示す簡単な例を以下に示します。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
var distinctNumbers = numbers.Distinct();
foreach (var number in distinctNumbers)
{
Console.WriteLine(number);
}
}
}
上記の例では、重複要素を含む整数リストをまず作成しました。その後、Distinctメソッドを使用してユニークな要素を取得し、それをコンソールに出力しました。出力結果は以下の通りです:
1
2
3
4
5