Saving ObservableCollection to file (.txt)
Whats the best way for me to save an observableCollection of data that I have displayed in a listview to a file(.txt). I had it working when I didnt have the observableCollection and the binding data s开发者_运维百科hown below, for this i simply used a string builder. From the code below how can i save the "Process name"
XAML code
<ListView Height="146" ScrollBar.Scroll="listView1_Scroll" ItemsSource="{Binding StatisticsCollection}"> <ListView.View>
<GridView >
<GridViewColumn Header="Process Name" Width="80" DisplayMemberBinding="{Binding ProcessName}" />
</GridView>
</Listview.View>
Stringbuilder that use to work
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (object item in listView1.Items)
{
sb.AppendLine(item.ToString());
}
Declaration
ObservableCollection<StatisticsData> _StatisticsCollection =
new ObservableCollection<StatisticsData>();
public ObservableCollection<StatisticsData> StatisticsCollection
{
get { return _StatisticsCollection; }
}
Any feedback would be great,
Thanks
Martin
You can do a similar foreach
loop for your ObservableCollection.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (StatisticsData item in StatisticsCollection)
{
sb.AppendLine(item.ToString());
}
From your naming of "_StatisticsCollection" I am assuming you save it as a field variable? If so, just iterate that instead, and write the "ProcessName" property to the file/StringBuilder. Alternatively, use the Linq.Enumerable extension method "Cast" to iterate the items as "StatisticsData" : foreach (var item in listView1.Items.Cast). Again, it is the property "ProcessName" you would want to write out.
Don't use any temp variables, it is unnecessary. Write directly to file:
using (var writer = new StreamWriter("text.txt"))
{
foreach (StatisticsData item in StatisticsCollection)
{
writer.WriteLine(item.ToString());
}
}
精彩评论