简体   繁体   English

使用字符串分隔逗号。使用LINQ加入

[英]Comma separated using string.Join with LINQ

I used string.Join in lambda expression to form comma seperated values 我使用string.Join在lambda表达式中形成逗号分隔的值

I achieved it using the following code: 我使用以下代码实现了它:

    var viewData = queue.Select(items => new companyQueueWithSegInfo()
{
 segmentName = string.Join(",", items.Select(i => i.seginfo.Trim()));

                                  }).AsQueryable()

}

The output for this will be : 输出为:

AB ,CD

But I need output as 但是我需要输出为

AB, CD

I tried like this: 我这样尝试过:

string.Join(" ,",items.Select(i => i.segminfo)).Replace(",", ", ").Replace(" ,","")

Can anyone help me with this? 谁能帮我这个? but it didn't work. 但这没用。

If seginfo is a string , how about Trim them first and then then join with ", " ? 如果seginfostring ,那么先Trim它们然后再用", " seginfo如何?

string.Join(", ", items.Select(i => i.seginfo.Trim()));

Also you should check your item is null or not for prevent NRE like; 另外,您应该检查您的商品是否为null ,以防止出现类似NRE的情况;

string.Join(", ", list.Where(s => s != null).Select(i => i.Trim()))

or can use IsNullOrEmpty as others mentioned. 或可以像其他人一样使用IsNullOrEmpty

You can use Trim() for removing all leading and trailing white-space characters. 您可以使用Trim()删除所有前导和尾随空格字符。 And then just change "," to ", " : 然后只需将","更改为", "

var result = string.Join(", ", items.Where(x => !String.IsNullOrEmpty(x))
                                   .Select(i => i.seginfo.Trim()));

Be sure to check if the string is empty or null also as I did. 确保像我一样检查字符串是否为空或null。

Try this using Trim() ie, you need to join them with ", " and then use the Trim(): 使用Trim()尝试此操作,即,需要将它们与", " ,然后使用Trim():

string.Join(", ",items.Select(i => i.seginfo.Trim()))

To handle NULL condition of string try this: 要处理字符串的NULL条件,请尝试以下操作:

string.Join(", ", items.Where(x => !String.IsNullOrEmpty(x))
                      .Select(i => i.seginfo.Trim()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM