虽然我想做的事情看起来很琐碎,但我找不到实现我想要的东西的方法。我知道存在多个问题,如何将类属性一起放入列表中,并像SO上那样用逗号分隔,但这些问题似乎都与我的情况无关。
我有一个类别Form
定义如下:
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
类属性创建了一个List<Form>
,然后我想创建一个字符串,其中所有这些类属性都用逗号分隔。在这种情况下,我使用基本的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
类中,您可以重写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") + ",";
}