简体   繁体   English

为什么LINQ无法将DataRows添加到DataTable?

[英]Why does LINQ not work to add DataRows to a DataTable?

To shoehorn ExpandoObjects into something grids like the following two attempts were made. 将ExpandoObjects鞋拔成网格,就像下面的两次尝试一样。

This doesn't work: 这不起作用:

var data = _d.Query<dynamic>(_script);         // returns IEnumerable<ExpandoObject>

IDictionary<string, object> c = (IDictionary<string, object>)data.FirstOrDefault();
DataTable dt = new DataTable();

dt.BeginLoadData();
dt.Columns.AddRange(c.Keys.Select(k => new DataColumn(k)).ToArray());
data.Select(r => dt.Rows.Add((r as IDictionary<string, object>).Values.ToArray()));
dt.EndLoadData();

But this does: 但这样做:

dt.Columns.AddRange(c.Keys.Select(k => new DataColumn(k)).ToArray());
foreach (IDictionary<string, object> r in data)
  dt.Rows.Add(r.Values.ToArray());

Why? 为什么?

Select Method 选择方法

The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic. 在通过直接调用其GetEnumerator方法或在Visual C#中使用foreach或在Visual Basic中使用For Each来枚举对象之前,不会执行此方法表示的查询。

So this select is never executed: 所以这个选择永远不会执行:

data.Select(r => dt.Rows.Add((r as IDictionary<string, object>).Values.ToArray()));

Reference http://msdn.microsoft.com/ru-ru/library/bb548891.aspx 参考http://msdn.microsoft.com/ru-ru/library/bb548891.aspx

我没有测试过这个,但是尝试这样的东西:

data.Cast<Dictionary<string, object>>().ToList().ForEach(x => dt.Rows.Add(x.Values.ToArray()));

As sailor already pointed out, LINQ is lazily evaluated. 正如水手已经指出的那样,LINQ被懒惰地评估了。 Placing a .LastOrDefault() on the end of your query will cause execution (because by trying to get the last element it will execute your Select() ), however it will make your code look even worse! 在查询结束时放置.LastOrDefault()将导致执行(因为尝试获取它将执行Select()的最后一个元素), 但是它会使您的代码看起来更糟!

By definition, LINQ Select should not be used for side-effecting behaviour. 根据定义,LINQ Select不应用于副作用行为。 I believe you should be able to see that in your question option 2 looks much cleaner than option 1. By reading option 2, I can easily understand, that you are adding each element of data to the datatable. 我相信你应该能够在你的问题中看到选项2看起来比选项1更清晰。通过阅读选项2,我可以很容易地理解,您正在将data每个元素添加到data中。 By reading option 1, I'd guess you're doing something to the data variable, which would be wrong. 通过阅读选项1,我猜你正在对data变量做些什么,这是错误的。

In conclusion, just stick with option 2. When performance is the same (as this is the case), try to make your code as "easy" to read as possible. 总而言之,只需坚持使用选项2.当性能相同时(就是这种情况),尽量使代码“易于”阅读。 A random person should be able to get the general idea without reading through the whole thing. 一个随机的人应该能够在不阅读整个事情的情况下获得一般性的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM