实体框架到 CSV 浮点值

本文关键字:CSV 框架 实体 | 更新日期: 2023-09-27 17:56:04

我正在尝试将一个对象写入csv,问题是我的对象具有示例(14,9)的浮点值,我想将它们更改为(14.9),这样就不会对csv格式造成任何问题

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());

实体框架到 CSV 浮点值

在您的情况下,最简单的方法是更改当前线程区域性,然后将其还原。

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

您还可以在
(prop.GetValue(entityObject, null) ?? "?").ToString()但在这种情况下,您可能需要检查prop.GetValue(entityObject, null)是否IFormattable(或者是单还是双打),然后应用指定InvariantCultureToString

我找到了解决方案,忘记更新这篇文章,这是通过更改线程文化

 System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
                customCulture.NumberFormat.NumberDecimalSeparator = ".";
                System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;