我有List<Accrual>
和List<Brand>
(以及许多其他类似对象),如下所述。我需要使用List<string>
String.Join
创建逗号分隔的字符串
public static string GetCommaSeparatedString(List<string> input)
{
return String.Join(",", input);
}
List<Accrual>
我需要传递List<Description>
方法List<Brand>
,我需要传递List<Name>
方法我们如何以最易读的方式以最少的代码行来实现它?
注意:我使用的是.Net 4.0
课程示例
public class Accrual
{
public string Code { get; set; }
public string Description { get; set; }
}
public class Brand
{
public int Number { get; set; }
public string Name { get; set; }
}
答案 0 :(得分:8)
首先,您可以覆盖ToString
方法:
public class Brand
{
public int Number { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
void Method()
{
var brands = new List<Brand>()
{
new Brand { Number = 1, Name = "a" },
new Brand { Number = 2, Name = "b" }
};
// outputs: a,b
Console.WriteLine(string.Join(",", brands));
}
其次,您可以使用Linq获取名称,然后加入它们:
var brandsNames = brands.Select(i => i.Name);
string joinedNames = string.Join(",", brandsNames);
如果你确实需要泛型方法,那么你可以使用它(尽管它没有给你任何东西,至少在这种情况下),这仍然是使用overrriden ToString
方法:
public static class Formatter
{
public static string GetCommaSeparatedString<T>(IEnumerable<T> input)
{
return string.Join(",", input);
}
}
// and then
string brandsStrings = Formatter.GetCommaSeparatedString<Brand>(brands);
// or just
string brandsStrings = Formatter.GetCommaSeparatedString(brands);
答案 1 :(得分:3)
好吧,首先我要更改GetCommaSeparatedString
方法签名以支持IEnumerable<string>
而不是List<string>
并将其转换为扩展方法:
public static string GetCommaSeparatedString(this IEnumerable<string> input)
{
return String.Join(",", input);
}
然后只需:
var accDescrs = listAccruals.Select(x => x.Description).GetCommaSeparatedString();
var brndNames = listBrands.Select(x => x.Name).GetCommaSeparatedString();
答案 2 :(得分:0)
public static string SeparateByCommas<T, TProp>(this IEnumerable<T> source, Expression<Func<T, TProp>> expression)
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
return string.Empty;
var propName = memberExpression.Member.Name;
return source.Aggregate(new StringBuilder(), (builder, t) =>
{
builder.Append(typeof (T).GetProperty(propName).GetValue(t).ToString());
builder.Append(",");
return builder;
}).ToString();
}
var test = new List<Brand>
{
new Brand
{
Number = 1,
Name = "a"
},
new Brand
{
Number = 2,
Name = "b"
}
};
string separateByCommas = test.SeparateByCommas(brand => brand.Name);