Вывод результата запроса в файл

Для данной программы реализовать вывод результата запроса в соответствии с вариантом (см. табл.) в файл.

Вариант: Вывести всю информацию по товарам, имеющимся в магазине (вводится пользователем)[отменено] Короче, я напутал вариант в таблице, мне просто нужно вывести в файл.

Код:

Program
static void Main(string[] args)
{
    Storage stock = new Storage(3);
    stock[0] = new Tovar("01", "Товар1", "Магазин5", 4300);
    stock[1] = new Tovar("02", "Товар2", "Магазин7", 5340);
    stock[2] = new Tovar("03", "Товар3", "Магазин3", 3040);

    bool auditor = true;
    while (auditor)
    {

        Console.WriteLine("\nВведите тип операции");
        Console.WriteLine("1) Найти товар по ID");
        Console.WriteLine("2) Найти товар по названию");
        Console.WriteLine("3) Отсортировать массив товаров по цене");
        Console.WriteLine("4) Отсортировать массив товаров по названию");
        Console.WriteLine("5) Отсортировать массив товаров по магазину");
        Console.WriteLine("6) Закончить");

        string number = Console.ReadLine();
        Console.WriteLine();

        switch (number)
        {
            case "1":
                string search_ID = Console.ReadLine();
                Tovar  item0 = stock.FindProductID(search_ID);
                if (item0 != null)
                    Console.WriteLine(item0.ToString());
                break;
            case "2":
                string search_name = Console.ReadLine();
                Tovar item1 = stock.FindProductName(search_name);
                if (item1 != null)
                    Console.WriteLine(item1.ToString());
                else Console.WriteLine("Нет такого");
                break;
            case "3":
                Tovar[] tests = stock.SortByCost();
                for (int i = 0; i < tests.Length; i++)
                {
                    Console.WriteLine(tests[i].ToString());
                }
                break;
            case "4":
                Tovar[] tests1 = stock.SortByName();
                for (int i = 0; i < tests1.Length; i++)
                {
                    Console.WriteLine(tests1[i].ToString());
                }
                break;
            case "5":
                Tovar[] tests2 = stock.SortByShop();
                for (int i = 0; i < tests2.Length; i++)
                {
                    Console.WriteLine(tests2[i].ToString());
                }
                break;
            case "6":
                auditor = false;        
                break;
        }
    }
    Console.WriteLine();
    
    Console.WriteLine("Сумма товаров:");
    Console.WriteLine(stock[0] + stock[1]);
    Console.ReadKey();
}
internal class Tovar
{
    public string ID { get; private set; } //что бы явно не обявлять резервную переменную
    public string Name { get; private set; }
    public string Shop { get; private set; }
    public double Cost { get; private set; }
    public Tovar(string id, string name, string shop, double cost)
    {
        ID = id;
        Name = name;
        Shop = shop;
        Cost = cost;
    }
    public override string ToString()
    {
        return $"ID: {ID}, название: {Name}, магазин: {Shop}, цена: {Cost}";
    }
    public static double operator +(Tovar obj1, Tovar obj2)
    {
        return obj1.Cost + obj2.Cost;
    }
}
internal class Storage
{
    Tovar[] products;
    public int Length { get; private set; }
    public Storage(int length)
    {
        Length = length;
        products = new Tovar[Length];
    }

    public Tovar this[int index]
    {
        get
        {
            if (IsValid(index))
                return products[index];
            throw new IndexOutOfRangeException();
        }
        set
        {
            if (IsValid(index))
                products[index] = value;
            else
                throw new IndexOutOfRangeException();
        }
    }

    public Tovar FindProductID(string id)
    {
        foreach (Tovar item0 in products)
        {
            if (item0.ID == id)
                return item0;
        }
        return null;
    }

    public Tovar FindProductName(string name)
    {
        foreach (Tovar item1 in products)
        {
            if (item1.Name == name)
                return item1;
        }
        return null;
    }
    public Tovar[] SortByName()
    {
        return products.OrderBy(n => n.Name).ToArray();
    }
    public Tovar[] SortByShop()
    {
        return products.OrderBy(n => n.Shop).ToArray();
    }
    public Tovar[] SortByCost()
    {
        return products.OrderBy(n => n.Cost).ToArray();
    }
    private bool IsValid(int index)
    {
        return (index >= 0) && (index < Length);
    }
}

Вопрос: Что необходимо добавить в код что бы выводить всю информацию в файл?


Ответы (1 шт):

Автор решения: 1843

Короче, вспомнил про streawriter

Код для while в Program

while (auditor)
{

    Console.WriteLine("\nВведите тип операции");
    Console.WriteLine("1) Найти товар по магазину");
    Console.WriteLine("2) Закончить");

    string number = Console.ReadLine();
    Console.WriteLine();

    switch (number)
    {
        case "1":
            string search_ID = Console.ReadLine();
            Tovar  item0 = stock.FindProductID(search_ID);
            if (item0 != null)
                Console.WriteLine(item0.ToString());
                using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
                {
                    sw.WriteLine(item0.ToString());
                }
            break;
        case "2":
            auditor = false;        
            break;
    }
}

И код для FindProductID в Storage

 public Tovar FindProductID(string id)
 {
     foreach (Tovar item0 in products)
     {
         if (item0.Shop == id)
             return item0;
     }
     return null;
 }

P.s А я уже говорил, что я "очень" сообразительный?(сарказм)

→ Ссылка