【发布时间】:2020-03-27 21:43:47
【问题描述】:
我有一个变量定义为 List
例子:
public class Car
{
public int CarId { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public string Color { get; set; }
}
public void AssignData()
{
List<Car> cars = new List<Car>();
cars.Add(new Car { CarId = 1, Brand = "Hundai", Model = "i10", Color = "White" });
cars.Add(new Car { CarId = 2, Brand = "Hundai", Model = "i20", Color = "Blue" });
}
我的预期输出将是一个带有“,”作为分隔符的文本文件。
执行的输出:
1,Hundai,i10,White
2,Hundai,120,Blue
我已经使用propertyinfo类尝试了下面的代码,但我觉得它没有效率,因为有一个嵌套循环
下面是尝试过的:
using (StreamWriter file = new StreamWriter(@"D:\WriteLines.txt", true))
{
foreach (Car car in allCars)
{
PropertyInfo[] properties = car.GetType().GetProperties();
string fullLine = string.Empty;
foreach (PropertyInfo property in properties)
{
fullLine += property.GetValue(car, null).ToString() + ",";
}
file.WriteLine(fullLine);
}
}
【问题讨论】:
-
我们期待一些解决方案的尝试。我们不只是提供解决方案。我们帮助您修复代码。请试一试。
-
File.WriteAllLines(@"c:\myFile.txt", cars.Select(car => string.Join(",", car.CarId, car.Brand, car.Model, car.Color)); -
@Dymitry Bychenko 展示的解决方案可能是最快和最小的 :)
-
@DmitryBychenko 的解决方案可能是最简单的。您还可以覆盖 ToString() 方法,然后直接在该对象列表上执行 string.join。
-
@DmitryBychenko - 你能建议我如何为通用类做点什么
标签: c# concatenation