开发者

List<long> to comma delimited string in C#

This often comes up. I h开发者_C百科ave a List and I want to go to a comma delimited string of all the elements in the list that I can use in SQL.

What is the most elegant way to do this in C#? Iterating over all of them is fine, except either the first or last element has to be special-cased since I don't want leading or trailing commas.

Got a good one-liner?


string.Join is your friend...

var list = new List<long> {1, 2, 3, 4};
var commaSeparated = string.Join(",", list);


List<long> items = // init here
string result = string.Join(", ", items.Select(i => i.ToString()).ToArray());

Not sure if it's the most elegant way, but it is a 1 liner!

Now there is also a string.Join that accepts an IEnumerable<T>, so it gets even shorter:

string result = string.Join(", ", items);

Thanks to type inference, you don't need to specified Join<long>


string.Join(",", Array.ConvertAll(list.ToArray(), item => item.ToString()));

(written directly into the post, so I may have got a couple of the parameters wrong, but you get the idea)


If you were to do it manually you shouldn't have special cases for both first and last value, instead you could just do this:

List<long> junk = // have some values here;
string separator = string.Empty;
string list = string.Empty;

foreach(long john in junk)
{
    list += separator + john.ToString();
    separator = ", ";
}

Not saying you should do this, regard this just as a comment.


// Content IDs
List<long> cIds = new List<long>();
cIds.Add(1);
cIds.Add(2);
cIds.Add(1);
cIds.Add(3);
cIds.Add(3);
string ids = string.Join(",", cIds.Distinct().Select(x => x.ToString()).ToArray());
// The example return the following output:
// ids = "1,2,3"

returns a list of unique items comma delimited.


    public static string CommaSeparate(this IEnumerable<string> values)
    {
        if (values.Count() == 0) return "[none]";
        return string.Join(", ", values.ToArray());
    }

This is an extension method that I use to do this in my applications. It's based on IEnumerable but should be similar for List.


I believe String.Join does that.


List<long> list =new List<long>(){1,2,3,4,5,6,7};

StringBuilder str =new StringBuilder();    

foreach(var i in list)
{
str.Append(i).Append(',');
}

This will Append the long values in (stringBuilder) str as

Ans: str = 1,2,3,4,5,6,7

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜