CSV字符串处理 [英] CSV string handling

查看:162
本文介绍了CSV字符串处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建 CSV 字符串(伪代码)的典型方式:


  1. 创建CSV容器对象(如C#中的StringBuilder)。

  2. 循环浏览您要添加的字符串


  3. >代码示例:

      public string ReturnAsCSV(ContactList contactList)
    {
    StringBuilder sb = new StringBuilder );
    foreach(contact contact in contactList)
    {
    sb.Append(c.Name +,);
    }

    sb.Remove(sb.Length - 1,1);
    //sb.Replace(,,,sb.Length - 1,1)

    return sb.ToString();
    }



    我喜欢通过检查容器是否为空添加逗号的想法,但是这并不意味着更多的处理,因为它需要检查每次出现的字符串的长度?



    我觉得应该有一个更容易/更清洁/更高效删除最后一个逗号的方式。任何想法?

    解决方案

    您可以使用

      string [] strings = contactList.Select => c.Name).ToArray(); 
    string csv = string.Join(,,strings);

    显然,这一切都可以在一行中完成,但两个更清楚。


    Typical way of creating a CSV string (pseudocode):

    1. Create a CSV container object (like a StringBuilder in C#).
    2. Loop through the strings you want to add appending a comma after each one.
    3. After the loop, remove that last superfluous comma.

    Code sample:

    public string ReturnAsCSV(ContactList contactList)
    {
        StringBuilder sb = new StringBuilder();
        foreach (Contact c in contactList)
        {
            sb.Append(c.Name + ",");
        }
    
        sb.Remove(sb.Length - 1, 1);
        //sb.Replace(",", "", sb.Length - 1, 1)
    
        return sb.ToString();
    }
    

    I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

    I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

    解决方案

    You could use LINQ to Objects:

    string [] strings = contactList.Select(c => c.Name).ToArray();
    string csv = string.Join(",", strings);
    

    Obviously that could all be done in one line, but it's a bit clearer on two.

    这篇关于CSV字符串处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆