2016-08-05 9 views
-3

Ich mache eine Anwendung, die Informationen über Produkte speichert und lädt. Diese Produkte haben einen Produktnamen, Kundennamen und einen Firmware-Speicherort. Ich habe sie richtig zu speichern und zu laden, aber ich versuche jetzt einen Weg zu finden, wo ich nach einem Produkt auf seinen Namen suchen kann. Hier ist meine Produkte Klasse:Suchen einer Textdatei C#

//private product data 
    private string productName; 

    public string getProductName() 
    { 
     return this.productName; 
    } 

    public void setProductName (string inProductName) 
    { 
     this.productName = inProductName; 
    } 

    private string customerName; 

    public string getCustomerName() 
    { 
     return this.customerName; 
    } 

    public void setCustomerName (string inCustomerName) 
    { 
     this.customerName = inCustomerName; 
    } 

    private string firmwareLocation; 

    public string getFirmwareLocation() 
    { 
     return this.firmwareLocation; 
    } 

    public void setFirmwareLocation (string inFirmwareLocation) 
    { 
     this.firmwareLocation = inFirmwareLocation; 
    } 


    //constructor 
    public Product (string inProductName, string inCustomerName, string inFirmwareLocation) 
    { 
     productName = inProductName; 
     customerName = inCustomerName; 
     firmwareLocation = inFirmwareLocation; 
    } 


    //save method 
    public void Save (System.IO.TextWriter textOut) 
    { 
     textOut.WriteLine(productName); 
     textOut.WriteLine(customerName); 
     textOut.WriteLine(firmwareLocation); 
    } 

    public bool Save(string filename) 
    { 
     System.IO.TextWriter textOut = null; 
     try 
     { 
      textOut = new System.IO.StreamWriter(filename, true); 
      Save(textOut); 
     } 
     catch 
     { 
      return false; 
     } 
     finally 
     { 
      if (textOut != null) 
      { 
       textOut.Close(); 
      } 
     } 
     return true; 
    } 

    public static Product Load (System.IO.TextReader textIn) 
    { 
     Product result = null; 

     try 
     { 
      string productName = textIn.ReadLine(); 
      string customerName = textIn.ReadLine(); 
      string firmwareLocation = textIn.ReadLine(); 
     } 
     catch 
     { 
      return null; 
     } 
     return result; 
    } 


} 

}

Ich habe mich gefragt, wie ich durch die Datei einen Produktnamen suchen sagen suchen würde, und es würde ihn und zeigen Sie den Produktnamen, Kundenname und Firmware finden Lage

+1

Du hast nicht eine Frage stellen! Notieren Sie sich mein Downvote, aber vielleicht verbessern Sie dies, bevor Ihr Vertreter abgeschlachtet wird. –

+1

Liefert Ihre Load-Methode immer null oder sehe ich heute nicht gut? – user3185569

+0

Deserialisieren Sie Ihre Textdatei in ein Objekt/eine Klasse im Speicher, und Sie können eine LINQ-Abfrage dagegen ausführen. Sie haben nicht gezeigt, was Sie getan oder versucht haben. –

Antwort

2

Erstens einige Empfehlungen für die aktuelle Klasse ...

Die Save Funktion ist besonders schlecht für das Ziehen Daten aus der Datei erneut auslesen. Tun Sie dies statt:

public class Product { 
    // Note that I've added a constructor for this class - this'll help later 
    public Product(string productName, string customerName, string firmwareLocation) { 
     this.productName = productName; 
     this.customerName = customerName; 
     this.firmwareLocation = firmwareLocation; 
    } 

    public void Save (System.IO.TextWriter textOut) 
    { 
     textOut.WriteLine(String.Format(
      "{0},{1},{2}", this.productName, this.customerName, this.firmwareLocation); 
    } 
} 

Also anstatt diese zu bekommen:

... 
Awesome Hairdryer 
Nick Bull 
C://hair.firmware 
Awesome TV 
Nick Bull 
C://tv.firmware 
... 

Sie diese:

... 
Awesome Hairdryer,Nick Bull,C://hair.firmware 
Awesome TV,Nick Bull,C://tv.firmware 
... 

Sobald Sie das getan haben ...

Es ist eine wirklich einfache Frage. Ein Liner, mit einigen Beispielen von Verfahren verwendet als Filter für die "Suche", wenn Sie wollen, dass sie:

IEnumerable<string> lines = File.ReadLines(pathToTextFile) 
    .TakeWhile(line => line.Contains("Nick Bull")); 

EDIT: Auch ordentlicheres Einzeiler, Zurückgeben einer Product Sammlung:

List<Product> lines = File.ReadLines(pathToTextFile) 
    .TakeWhile(line => line.Contains("Nick Bull")) 
    .Select(line => new Product(line.Split(',')[0], line.Split(',')[1], line.Split(',')[2]) 
    .ToList(); 

Um sie durchlaufen und andere, kompliziertere Dinge zu tun, könnte man sie alle dann tun Sachen lesen:

var lines = File.ReadAllLines(filePath); 
var products = new List<Product>(); 

foreach (string line in lines) { 
    if (Regex.IsMatch(line, @"super awesome regex")) { 
     string[] lineItems = line.Split(','); // Splits line at commas into array 
     products.Add(new Product(line[0], line[1], line[2]); // Thanks to our constructor 
    } 
} 

foreach (var product in products) { 
    Console.WriteLine(String.Format("Product name: {0}", product.productName)); 
} 

Suchfunktion Update

zu suchen, verwenden diese Funktionen:

public enum ProductProperty { 
    ProductName, 
    CustomerName, 
    FirmwareLocation 
} 

List<Product> GetAllProductsFromFile(string filePath) { 
    if (!File.Exists(filePath)) throw FileNotFoundException("Couldn't find " + filePath); 

    return File.ReadLines(filePath) 
     .Select(line => new Product(line.Split(',')[0], line.Split(',')[1], line.Split(',')[2]) 
     .ToList(); 
} 

function SearchProductsByProperty(IEnumerable<Product> products, ProductProperty productProperty, string value) { 
    return products.ToList().Where(product => 
     (productProperty == ProductProperty.ProductName) ? product.productName == productName : 
     (productProperty == ProductProperty.CustomerName) ? product.customerName == customerName : 
     (productProperty == ProductProperty.FirmwareName) ? product.firmwareName == firmwareName : throw new NotImplementedException("ProductProperty must be ProductProperty.ProductName, ProductProperty.CustomerName or ProductProperty.FirmwareName"); 
    ); 
} 

Dann:

var products = GetAllProductsFromFile(filePath); 
var searchedProducts = SearchProductsByProperty(products, ProductProperty.ProductName, "Awesome TV"); 

foreach (var product in searchedProducts) { 
    // Each product will have a `ProductName` equal to "Awesome TV". 
    // Finally, get the customer name by doing this within this foreach loop, using `product.customerName` 
    Console.WriteLine(product.customerName); 
} 
+0

Ich habe es googelt, ich habe eine Idee, wie Sie den Produktnamen finden, aber ich muss in der Lage sein, den richtigen Kundennamen und Firmware-Speicherort anzuzeigen, die mit ihm – lucycopp

+1

@lucycopp Dann d weiß, dass diese Antwort es ermöglicht, alle Zeilen in ein Array zu bringen, optional jede Zeile zu durchsuchen (mit '.TakeWhile (line => line.Contains (" Ich möchte, dass die Zeile dieses enthält) ")), und dann d haben alle Daten in dieser Zeile bereit zum Suchen und Parsen! –

+0

Vielen Dank das ist wirklich hilfreich, gibt es einen Weg, so dass ich den Namen suchen könnte und es würde mir den Firmware-Speicherort sagen, weil schließlich das sein wird, wofür ich es verwenden werde, so dass der Benutzer eingeben kann, welches Produkt sie wollen und die richtige Firmware wird – lucycopp