String.Join()方法

join需要2个参数,一个是分隔符,一个list数组;
var voucherGuid = string.Join(",", vouchers.Select(i => i.VouchGUID).Distinct());
执行后voucherGuid =‘1524ef61-4dbd-4a94-41d0-08d8075a7db4,3cf2f999-8809-41f3-f581-08d80885e63c’

String.Join()的源代码,大佬可以研究下

/// <summary>Concatenates the members of a collection, using the specified separator between each member.</summary>
/// <param name="separator">The string to use as a separator.<paramref name="separator" /> is included in the returned string only if <paramref name="values" /> has more than one element.</param>
/// <param name="values">A collection that contains the objects to concatenate.</param>
/// <typeparam name="T">The type of the members of <paramref name="values" />.</typeparam>
/// <returns>A string that consists of the members of <paramref name="values" /> delimited by the <paramref name="separator" /> string. If <paramref name="values" /> has no members, the method returns <see cref="F:System.String.Empty" />.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="values" /> is <see langword="null" />.</exception>
[ComVisible(false)]
[__DynamicallyInvokable]
public static string Join<T>(string separator, IEnumerable<T> values)
{
    
    
  if (values == null)
    throw new ArgumentNullException(nameof (values));
  if (separator == null)
    separator = string.Empty;
  using (IEnumerator<T> enumerator = values.GetEnumerator())
  {
    
    
    if (!enumerator.MoveNext())
      return string.Empty;
    StringBuilder sb = StringBuilderCache.Acquire(16);
    if ((object) enumerator.Current != null)
    {
    
    
      string str = enumerator.Current.ToString();
      if (str != null)
        sb.Append(str);
    }
    while (enumerator.MoveNext())
    {
    
    
      sb.Append(separator);
      if ((object) enumerator.Current != null)
      {
    
    
        string str = enumerator.Current.ToString();
        if (str != null)
          sb.Append(str);
      }
    }
    return StringBuilderCache.GetStringAndRelease(sb);
  }
}

猜你喜欢

转载自blog.csdn.net/q1923408717/article/details/112977567