【问题标题】:Object to comma separated string对象为逗号分隔的字符串
【发布时间】:2018-03-06 06:26:43
【问题描述】:

有没有办法让逗号与对象分开。注意它的对象不是对象列表

例如:

public class EmployeeLogReportListViewModel
{
    public DateTime Date { get; set; }
    public int EmployeeID { get; set; }
    public TimeSpan Time { get; set; }
    public int Sort { get; set; }
    public string Employer { get; set; }
}

具有以下值

Date = "2018/02/03"
EmployeeID = 111
Time = 11:53 AM
Sort = 1
Employer = EMP

这应该会导致

2018/02/03,111,11:53 AM,1 EMP

制作这个的最好方法是什么。可能的单行代码导致我不想使用字符串生成器并附加所有它。

【问题讨论】:

  • 你将如何使用它?
  • 你想在这里达到什么目的?
  • @Backs 将把它放在一个字符串列表中
  • 请看编辑后的文字

标签: c# string


【解决方案1】:

我认为您正在寻找 Overridden .ToString() 方法。你必须像这样修改类:

public class EmployeeLogReportListViewModel
{
    public DateTime Date { get; set; }
    public int EmployeeID { get; set; }
    public TimeSpan Time { get; set; }
    public int Sort { get; set; }
    public string Employer { get; set; }
    public override string ToString()
    {
        return String.Format("{0},{1},{2},{3},{4}", this.Date, this.EmployeeID, this.Time, this.Sort, this.Employer);
    }
}

Usage Example:

EmployeeLogReportListViewModel objVm = new EmployeeLogReportListViewModel();
// Assign values for the properties
objVm.ToString(); // This will give you the expected output

【讨论】:

  • 字符串插值也可以在 C# 6 中使用。
  • @SecretCoder 如果明天你想在类中添加一个新属性怎么办?您必须更改覆盖 ToString() 方法。您不处理它,新开发人员来了,只是忘记覆盖 ToString() 。它可能会在不多的地方导致错误/错误。只是一个想法。
  • 我喜欢这个例子的地方是它可以让你控制结果分隔字符串中值的顺序
【解决方案2】:

接受挑战

var o = new EmployeeLogReportListViewModel();
var text = string.Join
(
    ",",
    typeof(EmployeeLogReportListViewModel)
        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .Select
        (
            prop => prop.GetValue(o).ToString()
        )
);
Console.WriteLine(text);

从技术上讲,这是一条线。

如果您希望属性按字母顺序排序,您可以使用:

var o = new EmployeeLogReportListViewModel();
var text = string.Join
(
    ",",
    typeof(EmployeeLogReportListViewModel)
        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .OrderBy( prop => prop.Name )
        .Select
        (
            prop => prop.GetValue(o).ToString()
        )
);
Console.WriteLine(text);

【讨论】:

  • 这个答案最适合可扩展性。当您向类添加属性时,它可以在不更改任何内容的情况下工作。目前它抛出一个空引用异常,因为 Employer 为空。为了使用它,我们必须确保类的所有属性都不为空。否则我们会得到空引用。
  • 我喜欢这种方法,但是如果您希望它们按特定顺序进行修改,您将如何修改它?
  • @MikeMurphy 在Select 之前添加一个OrderBy 子句
【解决方案3】:

回复有点晚了,但我可以想象你想这样做是为了获得某种 csv 输出样式

一个很好的通用方法是创建一个扩展方法,将任何 Enumerable 转换为 csv 字符串。

所以借用@John Wu 的解决方案,我们想出了类似的东西

public static class EnumerableToCsvExtension
{
    public static string ToCSVString<TContent>(this IEnumerable<TContent> enumerable, char propertySeparator = ',', bool includeHeader = true)
    {
        var properties = typeof(TContent).GetProperties(BindingFlags.Instance | BindingFlags.Public);

        var header = string.Join(propertySeparator, properties.Select(p => p.Name));
        var rows = enumerable.ToList().ConvertAll(item => string.Join(propertySeparator, properties.Select(p => p.GetValue(item) ?? string.Empty )));

        var csvArray = includeHeader ? rows.Prepend(header) : rows;

        return string.Join(Environment.NewLine, csvArray);
    }
}

然后你像使用它

var list = new List<EmployeeLogReportListViewModel> { new EmployeeLogReportListViewModel(), new EmployeeLogReportListViewModel() };
list.ToCSVString();
list.ToCSVString(propertySeparator: '|', includeHeader: false);

【讨论】:

  • 有没有办法指定结果分隔字符串中值的顺序?
  • @MikeMurphy 可以通过添加一个额外的参数(如 params string[] order)轻松完成,然后对 properties 数组进行排序。为此,请查看如何在 c# 中对列表进行排序并发挥您的想象力:) 请参阅:stackoverflow.com/questions/1964234/…
  • 现在,如果您的问题是关于按名称排序,您可以使用 OrderBy 或 OrderByDescending
【解决方案4】:

你可以像下面这样使用:

public class bKashAccountInfo
{
    public string bKashNumber { get; set; }
    public string bKashAccountType { get; set; }

    public override string ToString()
    {
        return String.Format($"bKash Number-{bKashNumber}, Account Type - {bKashAccountType}");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2019-01-23
    相关资源
    最近更新 更多