开发者

How would I write this LINQ query?

开发者 https://www.devze.com 2023-03-09 15:19 出处:网络
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 unde开发者_开发百

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 unde开发者_开发百科rstand 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.


This will return an IEnumerable<DateTime> with all elements of the Date_Time column:

    table.Rows.Select(r=>((DateTime)r["Date_Time"]));


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


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());
 }


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


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

精彩评论

暂无评论...
验证码 换一张
取 消