簡體   English   中英

如何使用 Linq 查詢 DataTable 並按列集合分組?

[英]How do I query a DataTable using Linq and group by a collection of columns?

給定一個名為tableDataTable表,其中包含三列:“ID”(int)、“Parent”(int) 和“Description”(string),

並給出一個名為groupByColumnsList<string> ,其值為 { "ID", "Parent" }

如何構建按列表中所有列分組的 Linq 查詢?

我的困難的症結在於 GroupBy 需要匿名類型,而我不知道如何從列表中構建該類型。

我知道如何使用 Linq 查詢 DataTable以及如何按多列進行分組,但這需要我知道我按哪些列進行分組。 在這種情況下,我只是引用了列表中的某些列名。 下面的語句給出了我想要的結果,但它是硬編碼的。

var _attempt = table.AsEnumerable()
               .GroupBy(i => (i[groupByColumns[0]], i[groupByColumns[1]]))
               .Select(grp => new { GroupID = grp.Key, DataList = grp.ToList() })
               .ToList();

我不知道列表中會有多少值。 可能沒有——我可以根據需要為這種特殊情況編寫代碼,但列表中的字符串可能與 DataTable 中的列一樣多,直到運行時我才知道這兩個數字。

var table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Parent", typeof(int));
table.Columns.Add("Description", typeof(string));
// maybe more

table.Rows.Add(new object[] { 5, 1, "Whatever" });
// repeated

var groupByColumns = new List<string> ();
groupByColumns.Add("ID");
groupByColumns.Add("Parent");
// maybe more

var _attempt = table.AsEnumerable()
               .GroupBy(i => (i[groupByColumns[0]], i[groupByColumns[1]]))
               .Select(grp => new { GroupID = grp.Key, DataList = grp.ToList() })
               .ToList();

我不確定執行此操作的最佳方法是什么,但最簡單的方法之一是按由所有必需的列值組成的字符串進行分組。

這確實意味着組鍵是一個字符串而不是列值,但是您可以通過為每個組的第一個結果生成列值來解決這個問題。

例如

Func<DataRow, List<object>> GetColumnValues = r => groupByColumns.Select(key => r[key]).ToList();

var _attempt = table.AsEnumerable()
             .GroupBy(r => String.Join(":", GetColumnValues(r)))
             .Select(grp => new { GroupID = GetColumnValues(grp.First() ), DataList = grp.ToList() })
             .ToList();

這樣做的一個缺點是它可以執行大量字符串連接,因此如果行數非常大,則可能不適合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM