Reputation:
I'm trying to wrap my head around this "new concept" called LINQ. Ever heard of it? LOL
Anyway, I've read enough to know this can be written much clearer using LINQ, but I don't understand how I'd write it:
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);
}
EDIT [Title Change]: How would I write this using LINQ?
Apparently, this is not a query.
Upvotes: 2
Views: 194
Reputation: 20764
This will return an IEnumerable<DateTime>
with all elements of the Date_Time
column:
table.Rows.Select(r=>((DateTime)r["Date_Time"]));
Upvotes: 5
Reputation: 32750
I'm not sure you really need LINQ in this case, but if you really want to express what you are doing using LINQ, try this:
var query = from DataRow r in table.Rows select r["Date"];
foreach (var q in query)
{
Console.WriteLine(q.ToString());
}
Upvotes: 2
Reputation: 14409
In this specific case, LINQ might not actually be beneficial. See this post by Eric Lippert and the discussion on this previous SO question.
This is how you would do it, though.
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
Upvotes: 3
Reputation: 47978
foreach(DateTime dt in MySqlDateTimeQueryResult().AsEnumerable()
.Select(row => row.Field<DateTime>("Date_Time")))
Console.WriteLine(dt);
Upvotes: 2