9

当我生成逗号分隔的列表时,我讨厌我必须砍掉尾随的逗号。

有没有更好的办法?我经常这样做,所以寻找意见。

for(int x = 0; x < list.Count; x++)
{
  sb.Append(list[x].Name);
  sb.Append(",");
}

var result = sb.toString().Substring(0, result.length - 2);
4

5 回答 5

24

使用String.Join和 Linq 的IEnumerable.Select扩展方法。

var str = String.Join(",", list.Select(x => x.Name));
于 2013-03-07T21:28:22.007 回答
6

描述

您可以使用String.Joinand Enumerable.Select(namespace System.Linq) 方法

String.Join连接字符串数组的所有元素,在每个元素之间使用指定的分隔符。

Enumerable.Select将序列的每个元素投影到一个新表单中。

样本

String.Join(",", list.Select(x => x.Name));

更多信息

于 2013-03-07T21:28:29.163 回答
4

基本情况:

string.Join(",",list.Select(l => l.Name));

使用空检查:

string.Join(",",list.Where(l => l != null).Select(l => l.Name));

带有空/空检查:

string.Join(",",list.Where(l => !string.IsNullOrEmpty(l)).Select(l => l.Name));

修剪:

string.Join(",",list.Select(l => l.Name.Trim()));

既:

string.Join(",",list.Where(l => !string.IsNullOrEmpty(l)).Select(l => l.Name.Trim()));
于 2013-03-07T21:29:20.780 回答
1

如果性能是一个问题,我不建议这样做,但可以使用AggregateLINQ 的方法进行这样的连接。

例如

using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication14
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Example> list = new List<Example>()
            {
                new Example() { Name = "John Doe" },
                new Example() { Name = "Jane Doe" },
                new Example() { Name = "Fred Doe" },
            };

            string s = list.Select(item => item.Name)
                           .Aggregate((accumulator, iterator) => accumulator += "," + iterator);
        }
    }

    public class Example
    {
        public string Name { get; set; }
    }
}

但是,如果您的加入逻辑最终变得更加复杂(我怀疑这种情况很少发生),这可能很有用。

于 2013-03-07T22:39:19.970 回答
0

还有一个不雅的解决方案Join

for(int x = 0; x < list.Count; x++)
{
    if (x > 0)
        sb.Append(",");

    sb.Append(list[x].Name);
}


var result = sb.toString();
于 2013-03-07T22:26:38.403 回答