Search code examples
c#wpffile-ioobservablecollection

Writing the contents of an ObservableCollection to a text file


The goal of this question is to find out a way to obtain specific contents of an ObservableCollection (strings to be specific), and write them to a text file.

This collection is structured by using nodes because it is used to implement a TreeView. With that being said I am currently trying to obtain the child values of a parent node like so:

// I am currently getting an InvalidOperationException -- Sequence contains no matching element
var Node = Collection.GetAllChildren(x => x.Children)
                     .Distinct().ToList()
                     .First(x => x.DisplayName == Name);

In order to write to the file I am using this File. method: File.WriteAllLines(). It is my understanding that this method takes the FileName, and then an IEnumerable (a List, etc.). Does ObservableCollection contain a method that is IEnumerable compatible or do I need to add the contents to a List?

Right now I am trying this for the write to file line:

File.WriteAllLines(FileName, new ObservableCollection<string> { ViewModel.Data.ToList() });

How can I correct these two detrimental parts of my code? What is the correct way to get the information I need, and then add it to the file?

Update: These are the current errors that I receive on the above^ line of code. If I am implementing this correctly (which I am, based on the answers), why am I receiving these compile errors? (note: type has been switched to string)

Update 2: I've updated the argument to be written to the file. Data is an ObservableCollection<ViewModel>.

enter image description here


Solution

  • Yes, an overload of File.WriteAllLines takes IEnumerable<string>. ObservableCollection<string> implements IEnumerable<string>, so things should work.

    Just Type should be string:

    File.WriteAllLines(FileName, new ObservableCollection<Type> ( NodeName.ToList() ));
    

    Does ObservableCollection contain a method that is IEnumerable compatible

    No, it implements IEnumerable.

    PS: as it is suggested in another answer, ObservableCollection is redundant. You may pass anything which implements IEnumerable<string>.