我有一个以mvvm方式绑定到可观察集合的datagridview。 我正在试图找出如何将集合写入csv文件。
我可以格式化标题并将其放入,但不确定如何迭代集合并取出值并将它们放入带逗号分隔的文件中。
这是我的班级
public class ResultsModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Phone { get; set; }
public string Username { get; set; }
public bool Sucess { get; set; }
public string MessageType { get; set; }
public string SenderMessageSent { get; set; }
public string SenderMessageReceived { get; set; }
}
加载到一个可观察的集合
答案 0 :(得分:2)
这是一个通用的辅助方法,它利用反射来获取对象集合中所有属性的值,并序列化为逗号分隔值字符串。 (1行=来自集合的1个对象)
public static IEnumerable<string> ToCsv<T>(IEnumerable<T> list)
{
var fields = typeof(T).GetFields();
var properties = typeof(T).GetProperties();
foreach (var @object in list)
{
yield return string.Join(",",
fields.Select(x => (x.GetValue(@object) ?? string.Empty).ToString())
.Concat(properties.Select(p => (p.GetValue(@object, null) ?? string.Empty).ToString()))
.ToArray());
}
}
以及示例用法:
var oemResultsModels = new List<OemResultsModel>
{
new OemResultsModel
{
FirstName = "Fname1",
LastName = "LName1",
MessageType = "Type1",
Phone = 1234567,
SenderMessageReceived = "something1",
SenderMessageSent = "somethingelse1",
Sucess = true,
Username = "username1"
},
new OemResultsModel
{
FirstName = "Fname2",
LastName = "LName2",
MessageType = "Type2",
Phone = 123456789,
SenderMessageReceived = "something2",
SenderMessageSent = "somethingelse2",
Sucess = false,
Username = "username2"
}
};
using (var textWriter = File.CreateText(@"C:\destinationfile.csv"))
{
foreach (var line in ToCsv(oemResultsModels))
{
textWriter.WriteLine(line);
}
}