2011-10-16 48 views
-4

我想顯示每個名稱的最後一行。文本文件中有許多名稱,一個名稱包含超過50行。我想從文本文件中顯示每行的最後一行。如何顯示每個名稱文本文件的最後一行

請檢查這個鏈接,你會得到想法。

有黃油和蘋果的名字,。黃油含有9行,蘋果含有蘋果含有22行。我想在蘋果上顯示第9行黃油和第22行

在此先感謝。

我正在使用此代碼來顯示所有行,但我想顯示蘋果中的第9行黃油和第22行。

static void Main(string[] args) 
{ 
    int counter = 0; 
    string line; 

    // Read the file and display it line by line. 
    System.IO.StreamReader file = new System.IO.StreamReader("c:\\tra\\20100901.txt"); 
    while ((line = file.ReadLine()) != null) 
    { 
     if (line.Contains("apple")) 
     { 
      Console.WriteLine(counter.ToString() + ": " + line); 
     } 

     counter++; 
    } 

    file.Close(); 
} 
+1

那麼,你有什麼試圖做的? –

+0

我不明白你想做什麼,文本文件中的所有數字是什麼意思? – shuniar

+0

我想顯示蘋果,黃油,Lastlines –

回答

0
public static string ReturnTheNameBetweenCommas(string str) 
{ 
    int indexOfTheFirstComma = str.IndexOf(',');//find the first comma index 
    string strAfterTheFirstComma = str.SubString(indexOfTheFirstComma +1);//take the rest after the first comma 
    indexOfTheFirstComma = strAfterTheFirstComma.IndexOf(','); 
    string theNameBetweenFirstTwoCommas = strAfterTheFirstComma.SubString(0,indexOfTheFirstComma-1); 

    return strAfterTheFirstComma;  

} 

public class NameAndOccurence 
{ 
    public string Name{ get; set; } 
    public int Occurence{ get; set; } 
} 

public static void Method() 
{ 
    List<string> listOfLines = new List<string>(); 
    //Read all the lines to listOfLines one by one, use listOfLines.Add(line) every line as an element of the list 
    List<string> listOfDistinctNames = new List<string>(); 

    foreach(var item in listOfLines) 
    { 
     string nameInTheLine = ReturnTheNameBetweenCommas(item); 

     if(!listOfDistinctNames.Contains(nameInTheLine)) 
     { 
      listOfDistinctNames.Add(nameInTheLine); 
     } 
    } 

    List<NameAndOccurence> listOfNameAndOccurence = new List<NameAndOccurence>(); 

    foreach(var nameStr in listOfDistinctNames) 
    { 
     NameAndOccurence nameAndOccr = new NameAndOccurence(); 

     int occurence = 0   

     foreach(var lineStr in listOfLines) 
     { 
      if(lineStr.Contains(nameStr)) 
      { 
       occurence++; 
      } 
      else 
      { 
       nameAndOccr.Name = nameStr; 
       nameAndOccr.Occurence = occurence; 

       listOfNameAndOccurence.Add(nameAndOccr);     
      } 
     } 

    } 
    //now you've got the names in the lines and how many times they occurred 
    //for example for the image you showed there are 10 lines with the name of Butter-1M 
    //so in your listOfNameAndOccurence you have an object like this 
    //nameAndOccurence.Name is "Butter-1M" and nameAndOccurence.Occurence is 10 
    //you've got one for Apple too. 
    //Well after that all you gotta do is writing the 10th line of the textfile for Butter-1M 

} 

是否清楚?

+0

我需要添加列表 listOfNameAndOccurence = new List (); –

+0

@SharrokG你不需要任何它只是類是NameAndOccurencce但創建新的實例時它是NameAndOccurence^_ ^。 – Bastardo

+0

@SharrokG我從類名刪除了一個c,它一定沒問題。 – Bastardo

相關問題