【问题标题】:c# IList not generating as intendedc#IList 未按预期生成
【发布时间】:2019-05-16 08:32:40
【问题描述】:

基本要点:用户浏览到 CSV,应用程序读取 CSV,解析做一些计算,然后吐出一个新的 csv。这是一个使用 c# 风格的 .net 的 Windows 窗体应用程序。

正在测试的 CSV 文件:

Position,Title3,Title1,Title2,Title4,Title5,,
1,P-D3101A,NAME 1,175,282.9280381,1 x 30 x 120
2,P-D3103A,NAME 2,37.2,60.14241724,30 x 16
3,P-D3102A,NAME 3,29.8,48.17860306,30 x 10
4,P-D2301A,NAME 4,35,56.58560762,30 x 16
5,P-D1201A,NAME 5,38,61.43580256,30 x 16
6,P-D2301D,NAME 6,32,51.73541268,30 x 16
7,A-D0636,NAME 7,8.5,13.74221899,30 x 1.5

上课:

class Equipment
{
    public string Title1 { get; set; }
    public double Title2 { get; set; }
    public string Title3 { get; set; }
}

和一个解析器(非常感谢 SO 社区):

static IList<Equipment> Parse(string[] input)
{
    var result = new List<Equipment>();

    var header = input[0].Split(',').Select(t => t.Trim().ToLower()).ToList();
    var title1Loc = GetIndexOf(header, "title1");
    var title2Loc = GetIndexOf(header, "title2");
    var title3Loc = GetIndexOf(header, "title3");


    foreach (var s in input.Skip(1))
    {
        var line = s.Split(',');
        result.Add(new Equipment
        {
            Title1 = line[title1Loc].Trim(),
            Title2 = double.Parse(line[title2Loc]),
            Title3 = line[title3Loc].Trim(),
        });
    }
    return result;
}

static int GetIndexOf(IList<string> input, params string[] needles)
{
    return Array.FindIndex(input.ToArray(), needles.Contains);
}

还有几个按钮,一个是获取文件并将其文件路径保存在字符串 referenceFile 中,另一个是解析数据:

private void button2_Click(object sender, EventArgs e)
    {
        string[] data = File.ReadAllLines(referenceFile);
        MessageBox.Show(string.Join(Environment.NewLine, data), "Your CSV");
    }

最终我想生成一个新的 CSV 文件,虽然它是空白的,但为了检查它从解析的数据中得到了什么,我使用了一个显示的消息框:

MyProject.Form1+设备

在新行上重复 7 次。所以它正确地遍历了我的 7 行文件,但实际上并没有生成我想要的。有什么我看不到的明显错误吗?

【问题讨论】:

  • 类的默认 ToString 实现将输出类的名称。

标签: c# .net list foreach windows-forms-designer


【解决方案1】:

您将需要 override the ToStringEquipment 类的方法来获得所需的输出,该输出指示您的类型的字符串表示应该是什么样子。

以下是它的示例:

class Equipment
{
    public string Title1 { get; set; }
    public double Title2 { get; set; }
    public string Title3 { get; set; }

    public override string ToString()
    {
       return $"{Title1},{Title2},{Title3}";
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多