对象以逗号分隔的字符串

时间:2018-03-06 06:26:43

标签: c# string

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

前:

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

最好的方法是什么?可能的单行代码导致我不想使用字符串构建器并附加所有代码。

4 个答案:

答案 0 :(得分:7)

我认为您正在寻找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

答案 1 :(得分:5)

接受挑战

"{key}"

从技术上讲,这是一行。

答案 2 :(得分:1)

回复有点晚了,但是我可以想象你想这样做以便拥有某种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);

答案 3 :(得分:0)

您可以像下面这样使用:

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}");
    }
}
相关问题