【问题标题】:"Smart" way to concatenate strings?连接字符串的“智能”方式?
【发布时间】:2018-02-01 17:25:21
【问题描述】:

我正在寻找一种用分隔符连接字符串的“智能”方式。显然我可以自己编写所有这些代码,所以我想知道是否有一种简单的方法(LINQ 或其他我不知道的方法)来做到这一点。

假设我有一组字符串(可以是任意数量的字符串):

string s1 = "a";
string s2 = "b";
string s3 = "c";

我想连接字符串,结果类似于a, b, c。这很容易,但有一点不同:如果任何字符串为空,我不想要额外的逗号。

例如,如果这是我的设置:

string s1 = "";
string s2 = "b";
string s3 = "c";

我希望结果为b, c(或者如果s1s2 均为空,则为c)。

有没有简单的方法来做到这一点?

【问题讨论】:

  • string.join ..........可能会抛出一个 .where(s=>!string.isnullorempty(s))
  • @pm100 听起来不错——你能举个例子来回答吗?

标签: c# string concatenation


【解决方案1】:
var list = new List<string>{"a","b","", null};
var res = string.Join(", ", list.Where(s => !string.IsNullOrEmpty(s)));

【讨论】:

  • 太棒了!很简单! (我对其进行了编辑以为您修复语法和大写)
【解决方案2】:
string.Join(",", SOME_STRING_COLLECTION.Where(x => !string.IsNullOrWhiteSpace(x)));

【讨论】:

    【解决方案3】:

    使用string.Join(...):

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    namespace Rextester
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                string space = " ";
                string a = "One";
                string b = "Two";
                string c = "Three";
                var filteredList = (new List<string> { space, a, b, c }).Where(x => !string.IsNullOrWhiteSpace(x));
                string abc = string.Join(", ", filteredList);
                Console.WriteLine(abc); //One, Two, Three
                Console.ReadKey();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      • 2015-12-18
      • 1970-01-01
      • 2011-01-09
      • 2013-09-24
      相关资源
      最近更新 更多