c#linq csv更改最后一个元素的分隔符

时间:2015-06-12 00:26:44

标签: linq c#-4.0

考虑3个例子:

  1. 功能([" a"]) - >结果=" a",
  2. 功能([" a"," b"]) - > result =" a和b",
  3. 功能([" a"," b"," c"]) - >结果=" a,b和c"
  4. 是否有比以下更优雅或更有效的方法:

    result = fieldList.Aggregate((a, b) => a.Replace(" and ", ", ") + " and " + b);
    

    我假设fiedlList至少有一个元素。

    或传统节目:

    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < fieldList.Count; i++)
    {
        string field = fieldList[i];
        if (i == 0)
             sb.Append(field);
        else if (i == fieldList.Count - 1)
            sb.AppendFormat(" and {0}", field);
        else
            sb.AppendFormat(", {0}", field);
    }
    result = sb.ToString();
    

    我看不到top选项中的StringBuilder会起作用。

    我想到的唯一另一种方法是首先删除最后一个元素,然后在末尾追加:

    var last = fieldList.Last();
    fieldList.RemoveAt(fieldList.Count - 1);
    result = fieldList.Aggregate(new StringBuilder(), (sb, f) => { 
        if (sb.Length == 0) 
            sb.Append(f); 
        else
            sb.AppendFormat(", {0}", f);
        return sb;
    }).ToString();
    if (result.Length > 0)
        result += " and " + last;
    else
        result = last;
    

3 个答案:

答案 0 :(得分:0)

从@BikalBhattarai建议和@Darren在该帖子中发表的评论中被盗:

result = String.Join(", ", fieldList.ToArray(), 0, fieldList.Count - 1); 
if (fieldList.Count > 1) 
    result += " and " + fieldList.Last();

答案 1 :(得分:0)

这对我有用:

var result = String.Join(" and ", new []
{
    String.Join(", ", fieldList.Take(fieldList.Length - 1)),
    fieldList.LastOrDefault()
}.Where(x => x != null));

它甚至适用于空数组。

答案 2 :(得分:0)

其他解决方案

void Tokenize(const string& str,vector<string>& tokens, const string& delim)
{
       // Skip delimiters at beginning.
     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
     // Find first "non-delimiter".
     string::size_type pos     = str.find_first_of(delimiters, lastPos);

while (string::npos != pos || string::npos != lastPos)
 {
    // Found a token, add it to the vector.
    tokens.push_back(str.substr(lastPos, pos - lastPos));
    // Skip delimiters.  Note the "not_of"
    lastPos = str.find_first_not_of(delimiters, pos);
    // Find next "non-delimiter"
    pos = str.find_first_of(delimiters, lastPos);
  }
}