-3

I am a beginner and I want to be able to store and load options programmatically from a file, so that the options can be customized by players on the go.

I have tried the following things: I have tried to write the sorted list itself and I have tried to convert it to a string but none of these worked. I have searched using the Google search machine and I have searched on Stack Overflow too, but there wasn't anything of use for me.

Help would be greatly appreciated.

C4Oc
  • 1
  • 1
  • 1
  • That is a generic list and also only a list, not a SortedList, as in it does not have a key and a value. I asked for a non-generic SortedList so that I could store many different value types, so that I could easily have some sort of settings menu to change some things in my project – C4Oc Mar 07 '21 at 20:36
  • 1
    [How to Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) Als see [Why are there two kinds of SortedList?](https://stackoverflow.com/a/38314596/724039) – Luuk Mar 08 '21 at 10:21
  • SortedList in itself is another variable type entirely, you can do the following: SortedList sl = new SortedList();. There is also a generic variant where you use too. I know why a generic and non-generic exists too. – C4Oc Mar 09 '21 at 11:04
  • List has a function to write all. Just after the list object type.w then you will see that. – redParrot Mar 28 '21 at 19:50

1 Answers1

0

How about that?

using System.IO;

public static string FromListToString(SortedList list){
    string text = "";
    for (int i = 0; i < list.Count; i++){
        text += list.getKey(i) + "\t" list.getValue(i) + "\n";
    }
    return text;
}

public static SortedList FromStringToList(string str){
    string[] strArr = str.Split('\n');
    SortedList list = new SortedList();
    foreach (string i in strArr){
        string[] splittedStr = i.Split('\t');
        list.Add(splittedStr[0], splittedStr[1]);
    }
    return list;
}

public static void ToFile(string path, SortedList list){
    (new StreamWriter(path)).WriteLine(FromListToString(list));
}

public static SortedList FromFile(string path){
    return FromStringToList((new StreamReader(path)).Read());
}
Julian
  • 71
  • 6
  • In my post I meant a SortedList, as in a list but with value and key types, which can also be non-generic – C4Oc Mar 07 '21 at 20:38
  • 1
    This probably works for a SortedList that has a value type of string, but my problem is that I want to use strings and numbers (doubles) too. I have found a solution though, and it is to format it this way: type, key, value; as my key is always a string. Then upon loading you could use substrings and if conditionals to check for the value type to load the value correctly. – C4Oc Mar 09 '21 at 11:33