2025年1月5日 星期日

關於C# 的IEnumerable & IEnumerator二三話

會用這個是MAUI的其中一個範例,
目標是對某個資料夾內的*.note.txt作讀取檔名的動作,因為存檔後,要有取檔的動作,而Windows系統的習惯是開類似檔案總管的模式,自行選擇要開啟的檔案。也有些程式會以固定的副檔名作為標的,先讀取後,再列清單給使用者取用,而這個範例就是後者。

但不得不說說,這個語法簡化到令人不易理解的程度。這個先用了類似TList的IEnumerable結構,又使用的C# 專用的=>Lambda運算子,不太容易理解為何這麼寫,就可以達到

 
// Get the folder where the notes are stored.
string appDataPath = FileSystem.AppDataDirectory;

// Use Linq extensions to load the *.notes.txt files.
IEnumerable<note> notes = Directory

      // Select the file names from the directory
      .EnumerateFiles(appDataPath, "*.notes.txt")

      // Each file name is used to create a new Note
      .Select(filename => new Note()
      {
          Filename = filename,
          Text = File.ReadAllText(filename),
          Date = File.GetLastWriteTime(filename)
      })

      // With the final collection of notes, order them by date
      .OrderBy(note => note.Date);

// Add each note into the ObservableCollection
foreach (Note note in notes)
    Notes.Add(note);

想把它改寫成比較容易理解的模式,畢竟還是要讓未來的自己看得懂這段在寫什麼,然後知道如何改成新的需求。