[英]How would I write this LINQ query?
我正試圖圍繞這個名為 LINQ 的“新概念”。 聽說過嗎? 哈哈
無論如何,我已經閱讀了足夠多的內容,知道使用 LINQ 可以寫得更清楚,但我不明白我會怎么寫:
DataTable table = MySqlDateTimeQueryResult();
for (int i = 0; i < table.Rows.Count; i++) {
DataRow r = table.Rows[i];
DateTime dt = (DateTime)r["Date_Time"];
Console.WriteLine(dt);
}
編輯[標題更改]:我將如何使用 LINQ 編寫此內容?
顯然,這不是一個查詢。
這將返回一個IEnumerable<DateTime>
與Date_Time
列的所有元素:
table.Rows.Select(r=>((DateTime)r["Date_Time"]));
在這種特定情況下,LINQ 實際上可能沒有用處。 請參閱Eric Lippert 的這篇文章以及關於這個先前 SO 問題的討論。
不過,這就是你的做法。
table.Rows // Start with an IEnumerable
.Select(r => r["Date_Time"]) // Map each item to something, in this case extract the value
.ToList() // ForEach comes off of List, not IEnumerable
.ForEach(x => Console.WriteLine(x)); // Do something with each
foreach(DateTime dt in MySqlDateTimeQueryResult().AsEnumerable()
.Select(row => row.Field<DateTime>("Date_Time")))
Console.WriteLine(dt);
在這種情況下,我不確定您是否真的需要LINQ ,但是如果您真的想使用LINQ來表達您在做什么,請嘗試以下操作:
var query = from DataRow r in table.Rows select r["Date"];
foreach (var q in query)
{
Console.WriteLine(q.ToString());
}
var dates = table.AsEnumerable().Select(r => r["Date_Time"]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.