【问题标题】:Create comma separated list from list of objects从对象列表中创建逗号分隔列表
【发布时间】:2016-07-23 17:16:48
【问题描述】:

我有 Person 类型的对象列表。这个类有很多属性,我需要它们都放在一个逗号分隔的列表中,这样我以后可以将它用于 Csv 文件。

我已经用 foreach 管理了这个并添加了每个属性,用逗号分隔,等等。

const string commaSeparator = ",";
foreach (var item in individualsInformation)
{
    csv.AppendLine(item.ReferenceNumber + commaSeparator + item.FirstName + commaSeparator +
                   item.Surname + commaSeparator + item.MiddleName + commaSeparator +
                   item.Address1 + commaSeparator + item.Address2 + commaSeparator + 
                   item.Address3 + commaSeparator + item.Address4 + commaSeparator + 
                   item.City + commaSeparator + item.PostalCode + commaSeparator +
                   item.Country + commaSeparator + item.DateOfBirth.ToString() + commaSeparator +
                   item.ID + commaSeparator + item.Gender + commaSeparator +
                   item.Component + commaSeparator + item.NationalID + commaSeparator + 
                   item.SubSystemID + commaSeparator + item.System);
}

然后我意识到通过使用 string.Join 有很多有效的方法

这当然行不通:

string joined = string.Join(",", listOfPersons);

如果我选择这样的属性:

string joined = string.Join(",", listOfPersons(x => x.Id);

当然,我只为该属性获取逗号分隔列表。

有没有更有效的方法让每个属性用逗号分隔?

【问题讨论】:

  • 停止尝试重新发明轮子。查看答案here
  • 您当前的方法并不全是坏事,也是完全控制一切的唯一方法。

标签: c# list csv


【解决方案1】:

如果可能的话,我会避免反思。

您可以通过编译时安全性和可读代码轻松实现它:

IEnumerable<string> personTexts = listOfPersons
    .Select(p => String.Join(",", p.ReferenceNumber, p.FirstName, p.Surname, ...));
string joined = String.Join(Environment.NewLine, personTexts);

您可以完全控制应使用的属性以及使用顺序。

【讨论】:

    【解决方案2】:

    Reflection 是(有时)你的朋友:

    var props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); // todo: cache & filter not-needed props)
    
    var itemStr = string.Join(", ", 
                         props.Select(p => p.GetValue(item, null)?.ToString())
                              .ToArray());
    

    【讨论】:

    • 反思完全有帮助。谢谢! :) @nopeflow
    【解决方案3】:

    为您的 Person-Class 覆盖 ToString-Method

    public class Person
    {
        //properties...
    
        public override string ToString()
        {
            return string.Join(",",
                this.ReferenceNumber,
                this.FirstName,
                this.Surname,
                this.MiddleName,
                this.Address1,
                this.Address2,
                this.Address3,
                this.Address4,
                this.City,
                this.PostalCode,
                this.Country,
                this.DateOfBirth.ToString(),
                this.ID,
                this.Gender,
                this.Component,
                this.NationalID,
                this.SubSystemID,
                this.System);
        }
    }
    

    因此您可以使用Person.ToString() 生成csv。与反射方法不同,您可以轻松

    • 维持秩序
    • 处理不同的类型(BirthDate.ToString("d")Price.ToString("F2")
    • 跳过不需要的值,例如System.Collections.Generic.List1[System.String]
    • 根据您的要求更改值 (HasChildren ? "Yes" : "No")

    【讨论】:

      【解决方案4】:

      在 T : 类中使用反射

      var valueLines =reportData.Select(row => string.Join(",", header.Split(',').Select(a => row.GetType().GetProperty(a).GetValue(row,空))));

      例如

      private MemoryStream GenerateExcelStream(List<T> reportData)
          {
              var lines = new List<string>();
              var header = "";
              var attFilter = new NoDisplayInReportAttribute();
              PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
              foreach (PropertyDescriptor prop in properties)
                  if (!prop.Attributes.Matches(attFilter))
                      header += prop.Name + ",";
              header = header.Substring(0, header.Length - 1);
              lines.Add(header);
              var valueLines =reportData.Select(row => string.Join(",", header.Split(',').Select(a => row.GetType().GetProperty(a).GetValue(row, null))));
              lines.AddRange(valueLines);
              MemoryStream memoryStream = new MemoryStream();
              TextWriter tw = new StreamWriter(memoryStream);
              lines.ForEach(x => tw.WriteLine(x));
              tw.Flush();
              return memoryStream;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        相关资源
        最近更新 更多