输出到文件c#

时间:2017-04-04 21:36:41

标签: c# algorithm filewriter apriori

我正在使用Apriori算法来获得强有力的规则。到目前为止,我已将它们放在一个列表框中(程序在网上找到)。但是现在我想将输出保存到txt文件。到目前为止,我在.txt文件中的所有内容都是" AprioriAlgorithm.Rule"。它获得了正确数量的规则,因此重复了规则数量的" AprioriAlgorithm.Rule。例如,如果我有12个强规则,我会在txt文件中获得AprioriAlgoritm.Rule 12次。

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

    }
  }
}

这是输出类。

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

2 个答案:

答案 0 :(得分:2)

由于您要将Rule类型的对象而不是string传递给WriteLine方法,因此您必须指定要输出的确切内容。

您需要覆盖ToString()类的Rule方法才能执行此操作。

public class Rule
{
    public string RuleName { get; set; }
    public string RuleDescription { get; set; }

    public override string ToString()
    {
        return string.Format("{0}: {1}", RuleName, RuleDescription);
    }
}

正如documentation所说

  

通过调用该对象上的ToString方法写入对象的文本表示,然后是文本字符串或流的行终止符。

答案 1 :(得分:0)

另一种方法(覆盖ToString除外)是输出单个属性:

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

或者,使用C#的string interpolation功能:

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

如果您不能或不想覆盖ToString,则需要使用此功能。

相关问题