English 中文(简体)
为什么LINQ不努力在数据上添加数据。
原标题:Why does LINQ not work to add DataRows to a DataTable?

象以下两项尝试一样,将奥标扩大到一些电网。

这一工作:

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

但确实如此:

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

为什么?

最佳回答

<>载体>选择方法

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.

因此,这一选择从未执行过:

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

http://msdn.microsoft.com/ru-ru/library/bb548891.aspx” rel=“nofollow” http://msdn.microsoft.com/ru-ru/library/bb548891.aspx

问题回答

我对此进行了试验,但试图这样做:

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

正如行凶者已经指出的那样,准则准则得到认真评价。 登上. LastOrDefault(>,待你问询结束后,将执行(通过设法获得最后内容执行Select(),however。 这将使你的法典更糟!

顾名思义,《刑法》选择不应用于产生副作用的行为。 我认为,你们应当能够看到,在你们的提问中,选择2比选择更清洁。 1. 导言 通过阅读备选办法2,我很容易理解,你正在把<代码>数据的每个要素添加到数据表上。 通过阅读选项1,我猜测你在<代码>数据变量上做一些事情,这是错误的。

最后,仅仅坚持选择 2. 如果业绩相同(如上所述),则力求使你的代码尽可能成为“错误”。 随机人员应能在不读整个东西的情况下获得一般想法。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签