2011-10-16 20 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

相关问题