I'm trying to write an object to csv, the thing is that my objects have float valure for exemple (14,9) i want to change them to (14.9) so it won't cause any problem with the csv format
string csv = "";
using (var ctx = new NBAEntities2())
{
var studentList = ctx.TotalStat.SqlQuery("Select * from TotalStat where IDPlayer<5")
.ToList<TotalStat>();
List<object> mycollection = new List<object>();
string type = "";
foreach (var item in studentList)
{
type = item.GetType().ToString();
mycollection.Add(item);
}
string iteem = mycollection.First().ToString();
IEnumerable<PropertyInfo> props = mycollection.First().GetType().GetProperties();
//header
List<string> test = new List<string>();
csv += String.Join(",", props.Select(prop => prop.Name)) + "\r\n";
//rows
foreach (var entityObject in mycollection)
{
csv += String.Join(",", props.Select(
prop => (prop.GetValue(entityObject, null) ?? "?").ToString()
))
+ "\r\n";
}
}
File.WriteAllText("D:/Test.csv", csv.ToString());
Probably in your case the simplest way to do it is to change the current thread culture then restore it.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
You can also specify a format provider in
(prop.GetValue(entityObject, null) ?? "?").ToString()
but in this case you probably need to check if prop.GetValue(entityObject, null)
is IFormattable
(or if is a single or a double) then apply the ToString
specifying the InvariantCulture
.
I found the solution, forgot to update this post, it's by changing the thread culture
System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.