「東雲 忠太郎」の平凡な日常のできごと

2024/02/23(金)14:28

LinQでデータテーブルからRowsをソートした結果をデータテーブルで取得するコード

LINQ(39)

using System; using System.Data; using System.Linq; class Program {     static void Main()     {         // サンプルのデータテーブルを作成する         DataTable dt = new DataTable();         dt.Columns.Add("Column1", typeof(int));         dt.Columns.Add("Column2", typeof(string));         dt.Columns.Add("Column3", typeof(double));         dt.Rows.Add(3, "Row1", 10.5);         dt.Rows.Add(1, "Row2", 20.5);         dt.Rows.Add(2, "Row3", 30.5);         // LINQを使用して列1でデータテーブルの行をソートする         var sortedRows = dt.AsEnumerable()                            .OrderBy(row => row.Field<int>("Column1"))                            .CopyToDataTable();         // ソートされた行を出力する         foreach (DataRow row in sortedRows.Rows)         {             Console.WriteLine($"Column1: {row["Column1"]}, Column2: {row["Column2"]}, Column3: {row["Column3"]}");         }     } }

続きを読む

このブログでよく読まれている記事

もっと見る

総合記事ランキング

もっと見る