如何反转 ADO.NET 数据表的行顺序?
我有一个通过反序列化 JSON 消息获得的 DataTable。我事先不知道列名称是什么,因此我无法在特定列上使用 DataView.Sort。我只想颠倒行的顺序。这是我尝试过的:
var reversedTable = new DataTable();
for (var row = originalTable.Rows.Count - 1; row >= 0; row--)
reversedTable.Rows.Add(response.Messages.Rows[row]);
但这会抛出“System.ArgumentException:此行已经属于另一个表”。我怎样才能完成这个看似简单的任务呢?预先感谢,
弗兰克
回答:
var reversed = original.Clone();
for (var row = original.Rows.Count - 1; row >= 0; row--)
reversed.ImportRow(original.Rows[row]);
I have a DataTable that I have obtained by deserializing a JSON message. I do not know ahead of time what the column names will be so I cannot use DataView.Sort on a specific column. I would simply like to reverse the order of the rows. Here is what I tried:
var reversedTable = new DataTable();
for (var row = originalTable.Rows.Count - 1; row >= 0; row--)
reversedTable.Rows.Add(response.Messages.Rows[row]);
but this throws "System.ArgumentException: This row already belongs to another table." How can I accomplish this seemingly simple task? Thanks in advance,
Frank
ANSWER:
var reversed = original.Clone();
for (var row = original.Rows.Count - 1; row >= 0; row--)
reversed.ImportRow(original.Rows[row]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我以前见过那个错误消息......
不允许您直接将行从一个表添加到另一个表。首先,您必须克隆表,然后您可以遍历并为每一行调用 ImportRow()。
查看 geekzilla 以获得一个不错的示例。
我希望这有帮助!
I've seen that error message before.....
You're not allowed to directly add a row from one table to another. First you have to clone the table, then you can go through and call ImportRow() for each of the rows.
Check out geekzilla for a decent example.
I hope that helps!