user153923
user153923

Reputation:

How would I write this LINQ query?

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

Answers (5)

Mike
Mike

Reputation: 2922

 var dates = table.AsEnumerable().Select(r => r["Date_Time"]);

Upvotes: 0

thumbmunkeys
thumbmunkeys

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

InBetween
InBetween

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

David Ruttka
David Ruttka

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

manji
manji

Reputation: 47978

foreach(DateTime dt in MySqlDateTimeQueryResult().AsEnumerable()
                            .Select(row => row.Field<DateTime>("Date_Time")))
    Console.WriteLine(dt);

Upvotes: 2

Related Questions