方法 : 任意の単語またはフィールドを基準にテキスト データを並べ替える、またはフィルタ処理をする (LINQ)
更新 : 2007 年 11 月
次の例は、コンマ区切り値などの構造化されたテキスト行を、行の任意のフィールドを基準に並べ替える方法を示しています。フィールドは実行時に動的に指定できます。ここでは、scores.csv に学生の ID 番号を表すフィールドがあり、その後にテストの得点を表すフィールドが 4 つ続いているとします。
データを含むファイルを作成するには
- 「方法 : 異種ファイルのコンテンツを結合する (LINQ)」から scores.csv データをコピーし、ソリューション フォルダに保存します。
使用例
Class SortLines
Shared Sub Main()
Dim scores As String() = System.IO.File.ReadAllLines("../../../scores.csv")
' Change this to any value from 0 to 4
Dim sortField As Integer = 1
Console.WriteLine("Sorted highest to lowest by field " & sortField)
' Demonstrates how to return query from a method.
' The query is executed here.
For Each str As String In SortQuery(scores, sortField)
Console.WriteLine(str)
Next
' Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
Shared Function SortQuery(ByVal source As IEnumerable(Of String), ByVal num As Integer) _
As IEnumerable(Of String)
Dim scoreQuery = From line In source _
Let fields = line.Split(New Char() {","}) _
Order By fields(num) Descending _
Select line
Return scoreQuery
End Function
End Class
' Output:
' Sorted highest to lowest by field 1
' 116, 99, 86, 90, 94
' 120, 99, 82, 81, 79
' 111, 97, 92, 81, 60
' 114, 97, 89, 85, 82
' 121, 96, 85, 91, 60
' 122, 94, 92, 91, 91
' 117, 93, 92, 80, 87
' 118, 92, 90, 83, 78
' 113, 88, 94, 65, 91
' 112, 75, 84, 91, 39
' 119, 68, 79, 88, 92
' 115, 35, 72, 91, 70
public class SortLines
{
static void Main()
{
// Create an IEnumerable data source
string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv");
// Change this to any value from 0 to 4.
int sortField = 1;
Console.WriteLine("Sorted highest to lowest by field [{0}]:", sortField);
// Demonstrates how to return query from a method.
// The query is executed here.
foreach (string str in RunQuery(scores, sortField))
{
Console.WriteLine(str);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// Returns the query variable, not query results!
static IEnumerable<string> RunQuery(IEnumerable<string> source, int num)
{
// Split the string and sort on field[num]
var scoreQuery = from line in source
let fields = line.Split(',')
orderby fields[num] descending
select line;
return scoreQuery;
}
}
/* Output (if sortField == 1):
Sorted highest to lowest by field [1]:
116, 99, 86, 90, 94
120, 99, 82, 81, 79
111, 97, 92, 81, 60
114, 97, 89, 85, 82
121, 96, 85, 91, 60
122, 94, 92, 91, 91
117, 93, 92, 80, 87
118, 92, 90, 83, 78
113, 88, 94, 65, 91
112, 75, 84, 91, 39
119, 68, 79, 88, 92
115, 35, 72, 91, 70
*/
この例は、関数 (Visual Basic) またはメソッド (C#) からクエリ変数を返す方法も示しています。
コードのコンパイル方法
.NET Framework Version 3.5 を対象とする Visual Studio プロジェクトを作成します。プロジェクトには、System.Core.dll への参照と、System.Linq 名前空間に対する using ディレクティブ (C#) または Imports ステートメント (Visual Basic) が既定で含まれます。C# プロジェクトでは、System.IO 名前空間に対する using ディレクティブを追加します。
このコードをプロジェクト内にコピーします。
F5 キーを押して、プログラムをコンパイルおよび実行します。
任意のキーを押して、コンソール ウィンドウを終了します。