[英]How to save DataGrid data to CSV file without enumerating the query result again?
I am using this command to get data from my query: 我正在使用以下命令从查询中获取数据:
private void loadData()
{
numRows = 0;
try
{
data = gpso.gpEntitiesObject.ExecuteStoreQuery<My_Class>(sql);
dataGrid.ItemsSource = data;
dataGrid.IsReadOnly = true;
numRows = dataGrid.Items.Count;
numRowsTB.Text = "Number of rows: " + numRows;
}
catch (Exception ex)
{
statusBarTB.Text = "exception: " + ex.Message;
}
}
Although this works and I see the data in my DataGrid, I am not able to save the data to a CSV file since I am trying to reenumerate the query result again, which is not allowed. 尽管这可行并且我在DataGrid中看到了数据,但是由于试图重新枚举查询结果,所以无法将数据保存到CSV文件中,这是不允许的。
What would be the right way to get the data and save it to CSV? 什么是获取数据并将其保存到CSV的正确方法? Should I use the DataGrid API to scroll trough the rows and get the data in a foreach() loop?
是否应该使用DataGrid API滚动行并在foreach()循环中获取数据?
Here is my CSV function: 这是我的CSV函数:
public static string exportToCSV(IEnumerable<My_Class> data, string separator)
{
string ishod = "";
string csvRed = "";
ishod += "Key1" + separator + "Key2" + separator;
ishod += "Key3" + separator + "Key4" + separator;
ishod += "\n";
foreach (My_Class item in data)
{
csvRed += item.Key1+ separator + item.Key2+ separator;
csvRed += item.Key3+ separator + item.Key4+ separator;
csvRed += "\n";
ishod += csvRed;
csvRed = "";
}
return ishod;
}
I followed @Clemens advice. 我遵循@Clemens的建议。 I used
我用了
IEnumerable dataList = data.ToList<My_Class>();
dataGrid.ItemSource = dataList;
I then called 然后我打电话
exportToCSV(dataList, "\t");
with dataList as parameter and it worked! 与dataList作为参数,它的工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.