2017-05-05 69 views
3

我无法获取逻辑如何在文本文件中搜索,然后使用模型视图视图模型获取我需要的数据。 基本上,我必须做一个字典应用程序,我有文字文件中的文字,语言和描述。像:MVVM从文本文件中获取数据

猫,E英语;它是四条腿的动物

在模型中,我有一个文本框,客户端在其中写入一个单词和两个其他框,其中应该显示单词的语言和描述。

我只是无法得到如何在这个文件中搜索。我试图在网上搜索,但似乎没有满足我确切的问题。

回答

1

除非您的文件将发生变化,否则您可以在运行应用程序时将事先阅读整个文件并将数据放入视图模型的模型列表中。

由于这基本上是一个CSV文件,并假设每个条目是一条线,用分号作为分隔符,我们可以使用.NET CSV解析器将文件处理到您的机型:

基本模型:

public class DictionaryEntryModel { 
    public string Word { get; set; } 
    public string Language { get; set; } 
    public string Description { get; set; } 
} 

例视图使用构造模型,填写您的车型:

public class DictionaryViewModel { 

    // This will be a INotify based property in your VM 
    public List<DictionaryEntryModel> DictionaryEntries { get; set; } 

    public DictionaryViewModel() { 
     DictionaryEntries = new List<DictionaryEntryModel>(); 

     // Create a parser with the [;] delimiter 
     var textFieldParser = new TextFieldParser(new StringReader(File.ReadAllText(filePath))) 
     { 
      Delimiters = new string[] { ";" } 
     }; 

     while (!textFieldParser.EndOfData) 
     { 
      var entry = textFieldParser.ReadFields(); 
      DictionaryEntries.Add(new DictionaryEntryModel() 
       { 
        Word = entry[0], 
        Language = entry[1], 
        Description = entry[2] 
       }); 
     } 

     // Don't forget to close! 
     textFieldParser.Close(); 
    } 
} 

您现在可以使用属性DictionaryEntries绑定您的看法并且只要您的应用程序已打开,它将保留您的完整文件作为DictionaryEntryModel的列表。

希望这会有所帮助!

+1

非常感谢。它工作,我明白了,非常感谢! –

+0

@TatianaGancheva我很高兴它为你工作! :)如果你觉得它解决了你的问题,请考虑选择这个答案作为答案 –

0

我不在这里解决MVVM一部分,但只是如何搜索文本文件,以便根据搜索词来获得结果数据,使用不区分大小写的正则表达式。

string dictionaryFileName = @"C:\Test\SampleDictionary.txt"; // replace with your file path 
string searchedTerm = "Cat"; // Replace with user input word 

string searchRegex = string.Format("^(?<Term>{0});(?<Lang>[^;]*);(?<Desc>.*)$", searchedTerm); 

string foundTerm; 
string foundLanguage; 
string foundDescription; 

using (var s = new StreamReader(dictionaryFileName, Encoding.UTF8)) 
{ 
    string line; 
    while ((line = s.ReadLine()) != null) 
    { 
     var matches = Regex.Match(line, searchRegex, RegexOptions.IgnoreCase); 
     if (matches.Success) 
     { 
      foundTerm = matches.Groups["Term"].Value; 
      foundLanguage = matches.Groups["Lang"].Value; 
      foundDescription = matches.Groups["Desc"].Value; 
      break; 
     } 
    } 
} 

然后,您可以将结果字符串显示给用户。

请注意,这会为典型的输入字的工作,但它可能会产生奇怪的结果如果与正则表达式语法干扰用户输入特殊字符。其中大部分可以通过利用Regex.Escape(searchedTerm)来纠正。