搜索文本文件c#

时间:2016-08-05 10:28:03

标签: c# search

我正在制作一个保存和加载有关产品信息的应用程序。这些产品具有产品名称,客户名称和固件位置。我已经让它们正确保存和加载,但我现在正试图找到一种方法,我可以在其名称上搜索产品。 这是我的产品类:

    //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;
    }


}

}

我想知道如何搜索文件说搜索产品名称,它会找到并显示产品名称,客户名称和固件位置

1 个答案:

答案 0 :(得分:2)

首先,为您当前的课程提供一些建议......

Save函数再次从文件中提取数据非常差。这样做:

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);
    }
}

所以不要这样做:

...
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
...

一旦你做完了......

这是一个非常简单的问题。一个班轮,如果您需要,可以使用一些方法作为“搜索”过滤器的示例:

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

编辑:即使是整齐的单行,也会返回Product集合:

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();

要遍历它们并做其他更复杂的事情,你可以阅读它们然后做些事情:

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));
}

搜索功能更新

要搜索,请使用以下功能:

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);
}
相关问题