简体   繁体   English

实体框架为CSV浮点值

[英]Entity framework to CSV float values

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 我正在尝试将对象写入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());

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 . (prop.GetValue(entityObject, null) ?? "?").ToString()但是在这种情况下,您可能需要检查prop.GetValue(entityObject, null)是否为IFormattable (或者是一个或两个)应用ToString指定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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM