0

我有List<Accrual>List<Brand>(以及许多其他类似的对象),如下所述。我需要从List<string>using创建一个逗号分隔的字符串String.Join

    public static string GetCommaSeparatedString(List<string> input)
    {
        return String.Join(",", input);
    }
  1. List<Accrual>我需要将 a 传递List<Description>给方法的情况下
  2. List<Brand>我需要将 a 传递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; }
}
4

3 回答 3

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);

如果你真的需要通用方法,那么你可以使用这个(尽管它没有给你任何东西,至少在这种情况下),这仍然使用覆盖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);
于 2013-08-17T09:39:03.810 回答
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();
于 2013-08-17T09:41:37.343 回答
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);
于 2013-08-17T09:46:20.770 回答