Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

c# - 从IList <string>或IEnumerable <string>创建逗号分隔列表(Creating a comma separated list from IList<string> or IEnumerable<string>)

What is the cleanest way to create a comma-separated list of string values from an IList<string> or IEnumerable<string> ?

(从IList<string>IEnumerable<string>创建以逗号分隔的字符串值列表的最简洁方法是什么?)

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.

(String.Join(...)string[]操作,因此当IList<string>IEnumerable<string>无法轻松转换为字符串数组时,使用起来会非常麻烦。)

  ask by Daniel Fortunov translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.NET 4+

(.NET 4+)

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

Detail & Pre .Net 4.0 Solutions

(详细信息和Pre .Net 4.0解决方案)

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

(使用LINQ(.NET 3.5)可以非常轻松地将IEnumerable<string>转换为字符串数组:)

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

You can then call string.Join .

(然后你可以调用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 :)

(后者虽然有点满口:))

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 .

(这可能是最简单的方法,并且性能也非常高 - 还有其他问题,关于性能是什么样的,包括(但不限于) 这个 。)

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

(从.NET 4.0开始, string.Join有更多的重载,所以你实际上可以写:)

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

Much simpler :)

(更简单:))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...