创建自IList℃的逗号分隔的列表;串>或IEnumerable的<串GT; [英] Creating a comma separated list from IList<string> or IEnumerable<string>

查看:78
本文介绍了创建自IList℃的逗号分隔的列表;串>或IEnumerable的<串GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是创建一个的IList&LT字符串值的逗号分隔的列表最彻底的方法;串> 的IEnumerable<串>

的string.join(...)字符串操作[] 等都可以用繁琐的工作当类型,如的IList<串> 的IEnumerable<字符串方式> 不能很容易地转换成字符串数组

String.Join(...) operates on a string[] so can be cumbersome to work with when types such as IList<string> or IEnumerable<string> cannot easily be converted into a string array.

推荐答案

.NET 4 +

IList<string> strings = new List<string>{"1","2","testing"};
string joined = string.Join(",", strings);

详情&安培; pre .NET 4.0解决方案

的IEnumerable&LT;串&GT; 可以被转换成一个字符串数组的非常的轻松与LINQ(.NET 3.5):

IEnumerable<string> can be converted into a string array very easily with LINQ (.NET 3.5):

IEnumerable<string> strings = ...;
string[] array = strings.ToArray();

这是很容易,如果你需要编写相当于辅助方法:

It's easy enough to write the equivalent helper method if you need to:

public static T[] ToArray(IEnumerable<T> source)
{
    return new List<T>(source).ToArray();
}

然后调用它是这样的:

Then call it like this:

IEnumerable<string> strings = ...;
string[] array = Helpers.ToArray(strings);

您可以调用的string.join 。当然,你不这样做的有无的使用一个辅助方法:

You can then call string.Join. Of course, you don't have to use a helper method:

// C# 3 and .NET 3.5 way:
string joined = string.Join(",", strings.ToArray());
// C# 2 and .NET 2.0 way:
string joined = string.Join(",", new List<string>(strings).ToArray());

后者是有点拗口,但:)

The latter is a bit of a mouthful though :)

这很可能是做到这一点的最简单的方法,而且相当高性能以及 - 大约有性能正是等,包括其它问题,(但不限于)<一href=\"http://stackoverflow.com/questions/219519/whats-the-c-method-syntax-for-converting-an-array-to-a-simple-string\">this 之一。

This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) this one.

由于.NET 4.0,也有 更多可用的重载串。加入 ,所以实际上你可以这样写:

As of .NET 4.0, there are more overloads available in string.Join, so you can actually just write:

string joined = string.Join(",", strings);

简单多了:)

这篇关于创建自IList℃的逗号分隔的列表;串&GT;或IEnumerable的&LT;串GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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