2010-01-15 68 views
3

我有以下的扩展方法是获得一个列表并将其转换为一个逗号分隔的字符串:但是如何将这段代码转换为泛型?

static public string ToCsv(this List<string> lst) 
    { 
     const string SEPARATOR = ", "; 
     string csv = string.Empty; 

     foreach (var item in lst) 
      csv += item + SEPARATOR; 

     // remove the trailing separator 
     if (csv.Length > 0) 
      csv = csv.Remove(csv.Length - SEPARATOR.Length); 

     return csv; 
    } 

我想要做的事情类似,但它应用到列表(而不是字符串列表),编译器无法解析为T:

static public string ToCsv(this List<T> lst) 
    { 
     const string SEPARATOR = ", "; 
     string csv = string.Empty; 

     foreach (var item in lst) 
      csv += item.ToString() + SEPARATOR; 

     // remove the trailing separator 
     if (csv.Length > 0) 
      csv = csv.Remove(csv.Length - SEPARATOR.Length); 

     return csv; 
    } 

我错过了什么?

+0

FWIW,你的CSV代码是错误的;在某些情况下,您需要以CSV格式引用文本。 – 2010-01-15 01:03:22

+0

他没有说他想要一个“CSV”格式的文件,只是一个值为 – 2010-01-15 01:07:39

回答

8

首先,该方法的声明应该是:

public static string ToCsv<T>(this List<T> list) { // } 

注意,方法必须被参数化;这是方法名称后面的<T>

二,不要重新发明轮子。只需使用String.Join

public static string ToCsv<T>(this IEnumerable<T> source, string separator) { 
    return String.Join(separator, source.Select(x => x.ToString()).ToArray()); 
} 

public static string ToCsv<T>(this IEnumerable<T> source) { 
    return source.ToCsv(", "); 
} 

请注意,我已经通过接受IEnumerable<T>而不是List<T>的野生猪和广义的方法进一步。

在.NET 4.0中,你将能够说:

public static string ToCsv<T>(this IEnumerable<T> source, string separator) { 
    return String.Join(separator, source.Select(x => x.ToString()); 
} 

public static string ToCsv<T>(this IEnumerable<T> source) { 
    return source.ToCsv(", "); 
} 

也就是说,我们不要求的source.Select(x => x.ToString())结果转换为数组。

最后,有关此主题的有趣博客文章,请参阅Eric Lippert的文章Comma Quibbling

+0

的值的字符串,我的天哪,评论中的一些解决方案是巴洛克式的。 – Jimmy 2010-01-15 01:21:39

+0

“巴洛克式”或“破碎”? – 2010-01-15 02:12:19

7

尝试改变声明

static public string ToCsv<T>(this List<T> lst){ ... 
3

你的函数需要一个通用的参数:

static public string ToCsv<T>(this List<T> lst) 
          ^^^ 
2

你可以让这个更通用和使用,而不是一个列表< T> IEnumerable的,毕竟你不使用任何特定列表的方法

public static string ToCsv<T>(this IEnumerable lst);