搜索文本文件 c# [英] Searching a text file c#
问题描述
我正在制作一个应用程序,用于保存和加载有关产品的信息.这些产品具有产品名称、客户名称和固件位置.我已经让它们正确保存和加载,但是我现在正试图找到一种方法来搜索产品名称.这是我的产品类:
I am making an application which saves and loads information about products. These products have a product name, customer name and a firmware location. I have got them to save and load correctly, however I am now trying to find a way where I can search for a product on its name. Here is my products class:
//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;
}
}
}
我想知道如何搜索文件,比如搜索产品名称,它会找到它并显示产品名称、客户名称和固件位置
I was wondering how I would search through the file say search a product name, and it would find it and display the product name, customer name and firmware location
推荐答案
首先,给你目前班级的一些建议...
Save
功能对于再次从文件中提取数据非常糟糕.改为这样做:
The Save
function is exceptionally poor for pulling out data from the file again. Do this instead:
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);
}
}
所以,而不是得到这个:
So instead of getting this:
...
Awesome Hairdryer
Nick Bull
C://hair.firmware
Awesome TV
Nick Bull
C://tv.firmware
...
你明白了:
...
Awesome Hairdryer,Nick Bull,C://hair.firmware
Awesome TV,Nick Bull,C://tv.firmware
...
一旦你这样做了......
这是一个非常简单的问题.一个班轮,如果你想要的话,还有一些用作搜索"过滤器的方法示例:
It's a really easy question. One liner, with some examples of methods used as filters for "searching", if you want them:
IEnumerable<string> lines = File.ReadLines(pathToTextFile)
.TakeWhile(line => line.Contains("Nick Bull"));
EDIT:更简洁的单行代码,返回一个 Product
集合:
EDIT: Even neater one-liner, returning a Product
collection:
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();
要遍历它们并执行其他更复杂的操作,您可以全部阅读它们然后执行操作:
To iterate through them and do other more complicated stuff, you could read them all then do stuff:
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));
}
搜索功能更新
要搜索,请使用以下功能:
To search, use these functions:
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");
);
}
那么:
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);
}
这篇关于搜索文本文件 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!