2015-10-13 82 views
0

所以,我有一个文本文件,它看起来像这样:查找包含特定字符串的行和随机选择一个在C#

[hello]Hi 
[hello]welcome back 
[hello]Hello sir 
[goodbye]goodbye sir 
[goodbye]until next time 
... 

这里是代码的一部分:

string[] responseLines = File.ReadAllLines(@"responses.txt"); 
Random rand = new Random(); 
string response; 

case "hello": 
    chatBox.Items.Add(Me); 
    response = responseLines[rand.Next(responseLines.Length)]; 
    JARVIS.SpeakAsync(response); 
    chatBox.Items.Add("Jarvis: " + response); 
    break; 

问题是我只想找到包含[hello]的行,然后随机选择其中的一行。

回答

0

读取所有字符串文件后,分成两部分,其中不同的列表:

string[] responseLines = System.IO.File.ReadAllLines(@"responses.txt"); 
List<string> helloStrings = responseLines.Where<string>(str => str.StartsWith("[hello]")).Select(str => str.Replace("[hello]", "")).ToList<string>(); 
List<string> goodByeStrings = responseLines.Where<string>(str => str.StartsWith("[goodbye]")).Select(str => str.Replace("[goodbye]", "")).ToList<string>(); 

现在拿起从一个随机元素你需要的列表

+0

也可以!正是我正在寻找:) – techProdigy

+0

@techProdigy你可以请upvote答案? tks –

+1

我试过了,但我不能? Im新到这个网站。我认为我需要至少15个声望? – techProdigy

3

而不是

string[] responseLines = File.ReadAllLines(@"responses.txt"); 

使用

string[] responseLines = File.ReadAllLines(@"responses.txt").Where(s => s.Contains("[hello]")).ToArray(); 
+0

谢谢你回答!!作品! – techProdigy

相关问题