2013-11-28 40 views
0

假設我有一個文件,它包含以下內容:如何從文件中讀取某些數據並將其顯示出來?

Game Name: Candy Crush 
Game Type: Match Three 
Game Difficulty Rating: 8 

Game Name: Maplestory 
Game Type: RPG 
Game Difficulty: 6 

Game Name: Runescape 
Game Type: RPG 
Game Difficulty: 6 

Game Name: GTA 
Game Type: Video 
Game Difficulty: 7 

如何發佈僅一個消息框RPG遊戲?我想顯示列出的每個RPG遊戲的所有數據。

我剛纔試過這段代碼,但它似乎是顯示所有它。

private void button3_Click(object sender, EventArgs e) 
{ 
    var file = File.ReadAllText("Games.txt"); 
    var enter = Environment.NewLine; 

    var gamestrings = games.Select(x => string.Format("{0}\r\n{1}\r\n{2}", x.Name, x.Type, x.Difficulty)); 
    MessageBox.Show(string.Join(enter + enter, gamestrings)); 

    var games = file.Split(new[] { enter + enter }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Split(new[] { enter }, StringSplitOptions.RemoveEmptyEntries)).Select(e => new { Name = e[0], Type = e[1], Difficulty = e[2] }).Where(x => x.Type.Contains("RPG")); 
} 

給我的錯誤:

Cannot use local variable 'games' before it is declared 

A local variable named 'e' cannot be declared in this scope because it would give a  different meaning to 'e', which is already used in a 'parent or current' scope to denote something else 
+2

我建議你仔細閱讀[這篇文章](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

+0

@HighCore如果我只是嘗試閱讀整個文件而不是? – puretppc

+0

然後您需要在問題中發佈當前代碼,並指定您遇到問題的代碼的哪些部分,以及哪些/哪些不工作以及您的預期結果如何。 –

回答

2

首先,刪除StreamReader的東西,並留下這個:

var file = File.ReadAllText(@"c:\Games.txt"); 

(請確保你在裏面輸入正確的文件路徑!)

其次,由於你的數據文件有兩個Enter S離開,讓我們的這種優勢。讓我們將字符串分割成份這2分進入,然後除以重新每個輸入有每場比賽的細節到一個單一的記錄,爲此,我們將這個變量方便地定義:

var enter = Environment.NewLine; 

三,LINQ到拯救!!

您可以在lambda語法之間進行選擇:

var games = file.Split(new[] {enter + enter}, StringSplitOptions.RemoveEmptyEntries) 
       .Select(x => x.Split(new[] {enter}, StringSplitOptions.RemoveEmptyEntries)) 
       .Select(e => new {Name = e[0], Type = e[1], Difficulty = e[2]}) 
       .Where(x => x.Type.Contains("RPG")); 

或查詢語法:

var games = from g in file.Split(new[] {enter + enter}, StringSplitOptions.RemoveEmptyEntries) 
      let gamestrings = g.Split(new[] {enter}, StringSplitOptions.RemoveEmptyEntries) 
      let gamerecord = new {Name = gamestrings[0], Type = gamestrings[1], Difficulty = gamestrings[2]} 
      where gamerecord.Type.Contains("RPG") 
      select gamerecord; 

看到了嗎?現在您有包含3個屬性匿名類型的強類型列表:

  • 名稱
  • 類型
  • 難度

這些,你可以,好像他們是普通班操作和訪問他們屬性如下:

var gamestrings = games.Select(x => string.Format("{0}\r\n{1}\r\n{2}", x.Name, x.Type, x.Difficulty)); 
MessageBox.Show(string.Join(enter + enter, gamestrings)); 
+0

我試過Lambda語法,但它給了我2個錯誤。 – puretppc

+0

@puretppc你需要更具體。你得到什麼錯誤?我在我身邊工作得很好。 –

+0

@puretppc我使用'e'作爲lambda表達式參數,將其改爲另一個字母或變量名稱,因爲您已經有一個'e',它是Button事件參數。 –

0

你有一對夫婦與代碼和問題的問題。

FileStream inputFileStream = new FileStream("Games.txt", FileMode.Open, FileAccess.Read); 
StreamReader reader = new StreamReader(inputFileStream); 

這將打開一個流以從文件Games.txt中讀取內容。
您密切與流:

inputFileStream.Close(); 
reader.Close(); 

這應該以相反的順序來完成。但是,沒有必要關閉FileStreamStreamReader。關閉FileStream也將關閉StreamReader

一個更好的辦法是使用using關鍵字:

using (var inputFileStream = new FileStream("Games.txt", FileMode.Open, FileAccess.Read)) 
using (var reader = new StreamReader(inputFileStream)) 
{ 
    ... 
} 

在這樣做,所以你永遠不會忘記關門。

但是所有這些代碼在你的程序中是沒有用的。你完全不使用StreamReader
相反,你從Games.txt閱讀內容:

string contents = File.ReadAllText("Games.txt"); 

然後告訴它:

MessageBox.Show(contents); 

你真正想要做的是符合像讀行:

using (var inputFileStream = new FileStream("Games.txt", FileMode.Open, FileAccess.Read)) 
using (var reader = new StreamReader(inputFileStream)) 
{ 
    while (reader.Peek() >= 0) 
    { 
    var gameName = reader.ReadLine(); 
    var gameType = reader.ReadLine(); 
    var gameDifficulty = reader.ReadLine(); 
    var emptyLine = reader.ReadLine(); 

    // Here you'll insert the logic to filter out what you want to show. 
    } 
} 
+0

我編輯了我的第一篇文章,我試了你的代碼。但由於某種原因,它似乎沒有濾除任何東西。相反,它幾乎與我試圖讀取整個文件相同 – puretppc

0

以下是一種方法:

void Main() 
{ 
string[] lines = System.IO.File.ReadAllLines(@"C:\temp\test.txt"); 
var test = new List<string>(); 
foreach (var line in lines) 
{ 
    if (!string.IsNullOrWhiteSpace(line)) 
    { 
     var values = line.Split(':'); 
     test.Add(values[1].Trim()); 
    } 
} 

List<Game> games = new List<Game>(); 
for (int i = 0;i < test.Count();i = i + 3) 
{ 
    Game game = new Game(); 
    game.Name = test[i]; 
    game.Type = test[i+1]; 
    game.Difficulty = test[i+2]; 

    games.Add(game); 
} 
var rpgGames = games.Where(w => w.Type == "RPG"); 
} 

class Game { 
public string Name {get;set;} 
public string Type {get;set;} 
public string Difficulty {get;set;} 
} 
0

你也可以試試這個:

  1. 創建一個包含屬性的遊戲類:

    class Game 
    { 
        public string Name { get; set; } 
        public string Type { get; set; } 
        public string Difficulty { get; set; } 
    } 
    
  2. 然後在你的方法,添加以下代碼:

    var lines = File.ReadLines("test.txt"); 
    var games = new List<Game>(); 
    
    var currGame = new Game(); 
    foreach (string line in lines) 
    { 
        var parts = line.Split(':'); 
        if (parts.Length == 1) 
        { 
         games.Add(currGame); 
         currGame = new Game(); 
        } 
        else if (parts[0].EndsWith("Name")) 
         currGame.Name = parts[1].Trim(); 
        else if (parts[0].EndsWith("Type")) 
         currGame.Type = parts[1].Trim(); 
        else 
         currGame.Difficulty = parts[1].Trim(); 
    } 
    
    var output = string.Join(System.Environment.NewLine, games.Where(x => x.Type == "RPG") 
        .Select(x => string.Format("{0} [{1}] => Difficulty: {2}", x.Name, x.Type, x.Difficulty)) 
        .ToArray()); 
    Console.Write(output); 
    
相關問題