从LINQ中的字符串列表中生成CSV [英] Make CSV from list of string in LINQ

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

问题描述

我想采取一个列表集合,并生成一个单一的csv行。因此,请按此;

Hi I would like to take a list collection and generate a single csv line. So take this;

List<string> MakeStrings()
{
    List<string> results = new List<string>();
    results.add("Bob");
    results.add("Nancy");
    results.add("Joe");
    results.add("Jack");
    return results;       
}


string ContactStringsTogether(List<string> parts)
{
    StringBuilder sb = new StringBuilder();

    foreach (string part in parts)
    {
        if (sb.Length > 0)
            sb.Append(", ");

        sb.Append(part);
     }
     return sb.ToString();
}

这将返回Bob,Nancy,Joe,Jack

This returns "Bob,Nancy,Joe,Jack"

寻找关于LINQ的帮助,在单个语句中这样做。谢谢!

Looking for help on the LINQ to do this in a single statement. Thanks!

推荐答案

没有任何一个LINQ可以使用LINQ。请注意,您可以使用Aggregate方法来执行此操作,但是您将使用字符串连接而不是StringBuilder。如果你将经常做的事情,我会考虑添加一个扩展方法:

There are not any one liners to do this with LINQ. Note that you can use the Aggregate method to do this, but you will be using string concatenation instead of a StringBuilder. I would consider adding an extension method for this if it something you will be doing often:

    public static string ToCsv<T>(this IEnumerable<T> source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return string.Join(",", source.Select(s => s.ToString()).ToArray());
    }

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

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