Search code examples
c#algorithmfilewriterapriori

Output to file c#


I am using the Apriori Algorithm to get strong rules. So far I have got them in a list box(program was found online). However now I would like to save the output to a txt file. So far all I have been getting in the .txt file is "AprioriAlgorithm.Rule". It is getting the correct number of rules, thus repeating the "AprioriAlgorithm.Rule for the number of rules. For example, if I have 12 strong rules, I get AprioriAlgoritm.Rule for 12 times in the txt file.

namespace WPFClient
{
[Export(typeof(IResult))]
public partial class Result : Window, IResult
{
    public Result()
    {
        InitializeComponent();
    }

    public void Show(Output output)
    {
        FileStream fs = new FileStream("strongrules.txt", FileMode.Create);
        StreamWriter sw = new StreamWriter(fs);
        this.DataContext = output;
        for (int x = 0; x < output.StrongRules.Count; x++)
        {
            sw.WriteLine(output.StrongRules[x]);
        }

        this.ShowDialog();
        sw.Close();

    }
  }
}

And this is the output class.

namespace AprioriAlgorithm
{
using System.Collections.Generic;

public class Output
{
    #region Public Properties

    public IList<Rule> StrongRules { get; set; }

    public IList<string> MaximalItemSets { get; set; }

    public Dictionary<string, Dictionary<string, double>> ClosedItemSets { get; set; }

    public ItemsDictionary FrequentItems { get; set; } 

    #endregion
}
}

Solution

  • Another way to do this (other than overriding ToString) is to output the individual properties:

    var rule = output.StringRules[x];
    sw.WriteLine("{0}: {1}", rule.RuleName, rule.RuleDescription);
    

    Or, using the string interpolation feature of C#:

    sw.WriteLine($"{rule.RuleName}: {rule.RuleDescription}");
    

    You'd want to use this if you can't or don't want to override ToString.