从列表中添加 class 个属性并将它们放入字符串中,并以逗号作为分隔符

Add class properties from the List and put them into the string together with a comma as a delimiter

虽然我想做的事情看起来很琐碎,但我找不到实现我想要的方法。我知道存在多个问题如何将 class 属性一起放入列表并用逗号分隔,但其中 none 似乎与我的案例相关。

我有一个classForm定义如下:

public class Form
    {
        public string CustomerName { get; set; }
        public string CustomerAdress { get; set; }
        public string CustomerNumber { get; set; }
        public string OfficeAdress { get; set; }
        public string Date { get; set; }
        public Boolean FunctionalTest { get; set; }
        public string Signature { get; set; }


        public Form()
        {
        }
    }

MainPage.xaml.cs 中,我用 Form class 属性创建了一个 List<Form>,随后我想用所有这些 [=39] 创建一个字符串=] 以逗号分隔的属性。对于这种情况,我使用基本的 Join 方法和 Select 将任何类型的对象转换为字符串。

我在 MainPage.xaml.cs :

中通过 createCSV 方法做到这一点
void createCSV()
        {    
            var records = new List<Form>
        {
            new Form {CustomerName = customerName.Text,
                CustomerAdress = customerAdress.Text,
                CustomerNumber = customerNumber.Text,
                OfficeAdress = officeAdress.Text,
                Date = date.Date.ToString("MM/dd/yyyy"),
                FunctionalTest = testPicker.ToString()=="YES" ? true : false,
                Signature = signature.Text
            }
        };


            string results = String.Join(",", (object)records.Select(o => o.ToString()));
}

问题不是理想的结果是:"Mark Brown,123 High Level Street,01578454521,43 Falmouth Road,12/15/2020,false,Brown"

我得到:"System.Linq.Enumerable+SelectListIterator'2[MyApp.Form,System.String]"

PS。正如您所注意到的,我是 C# 的新手。不要对代码进行非建设性的批评,请提供有价值的回复,这将帮助我理解我做错了什么。

提前致谢

Form class 中,您可以覆盖 ToString() 方法并使用 System.Reflection 获取逗号字符串。

Form.cs

public class Form
{
    public string CustomerName { get; set; }
    public string CustomerAdress { get; set; }
    public string CustomerNumber { get; set; }
    public string OfficeAdress { get; set; }
    public string Date { get; set; }
    public bool FunctionalTest { get; set; }
    public string Signature { get; set; }

    public override string ToString()
    {
        string modelString = string.Empty;
        PropertyInfo[] properties = typeof(Form).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            var value = property.GetValue(this); // you should add a null check here before doing value.ToString as it will break on null
            modelString += value.ToString() + ",";
        }
        return modelString;
    }
}

代码

List<string> CSVDataList = new List<string>();
List<Form> FormList = new List<Form>();
...
foreach (var data in FormList)
{
    CSVDataList.Add(data.ToString());
}

现在您有一个字符串列表 CSVDataList,每个 Form 对象的数据都以逗号形式显示

P.S. 对于日期时间

var value = property.GetValue(this);
if(value is DateTime date)
{
   modelString += date.ToString("dd.MM.yyyy") + ",";
}