【问题标题】:Concatenate the properties of a List<Class> and write to file in C#连接 List<Class> 的属性并在 C# 中写入文件
【发布时间】:2020-03-27 21:43:47
【问题描述】:

我有一个变量定义为 List。我想用一些分隔符连接列表中单个类的属性并写入文件而不循环属性。

例子:

    public class Car
    {
        public int CarId { get; set; }
        public string Brand { get; set; }
        public string Model { get; set; }
        public string Color { get; set; }
    }

    public void AssignData()
    {
        List<Car> cars = new List<Car>();
        cars.Add(new Car { CarId = 1, Brand = "Hundai", Model = "i10", Color = "White" });
        cars.Add(new Car { CarId = 2, Brand = "Hundai", Model = "i20", Color = "Blue" });
    }

我的预期输出将是一个带有“,”作为分隔符的文本文件。

执行的输出:

1,Hundai,i10,White 2,Hundai,120,Blue

我已经使用propertyinfo类尝试了下面的代码,但我觉得它没有效率,因为有一个嵌套循环

下面是尝试过的:

using (StreamWriter file = new StreamWriter(@"D:\WriteLines.txt", true))
            {
                foreach (Car car in allCars)
                {
                    PropertyInfo[] properties = car.GetType().GetProperties();
                    string fullLine = string.Empty;
                    foreach (PropertyInfo property in properties)
                    {
                        fullLine += property.GetValue(car, null).ToString() + ",";
                    }
                    file.WriteLine(fullLine);
                }
            }

【问题讨论】:

  • 我们期待一些解决方案的尝试。我们不只是提供解决方案。我们帮助您修复代码。请试一试。
  • File.WriteAllLines(@"c:\myFile.txt", cars.Select(car =&gt; string.Join(",", car.CarId, car.Brand, car.Model, car.Color));
  • @Dymitry Bychenko 展示的解决方案可能是最快和最小的 :)
  • @DmitryBychenko 的解决方案可能是最简单的。您还可以覆盖 ToString() 方法,然后直接在该对象列表上执行 string.join。
  • @DmitryBychenko - 你能建议我如何为通用类做点什么

标签: c# concatenation


【解决方案1】:

好的。让我们概括这个问题(请参阅问题的 cmets):让我们加入 所有属性,它们是:

  1. public不是 static
  2. 可读可写
  3. 不是索引器(我们应该如何处理 this[int, int] 属性?)。
  4. 仅限指定类型(例如stringintdecimaldouble)(我们如何保存,比如IComparer&lt;int&gt; 类型的属性?)。

我们可以借助 ReflectionLinq 获得这些属性:

  using System.Linq;
  using System.Reflection;

  ...

  HashSet<Type> allowedTypes = new HashSet<Type>() {
    typeof(string), typeof(int), typeof(decimal), typeof(double)
  };

  var properties = typeof(Car)
    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
    .Where(prop => prop.CanRead && prop.CanWrite)
    .Where(prop => !prop.GetIndexParameters().Any())
    .Where(prop => allowedTypes.Contains(prop.PropertyType))
 // .Where(prop => ...) // Add here more coditions if required
    .ToArray();

现在,有了这些properties,我们可以将值保存到文件中:

  using System.IO;
  using System.Linq;

  ...

  File.WriteAllLines(@"D:\WriteLines.txt", cars
    .Select(car => string.Join(",", properties
       .Select(property => property.GetValue(car)))));

最后,您可以将这些部分组合成一个单个例程

  private static void SaveToFile<T>(IEnumerable<T> source, string fileName) {
    HashSet<Type> allowedTypes = new HashSet<Type>() {
      typeof(string), typeof(int), typeof(decimal), typeof(double)
    };

    var properties = typeof(T)
      .GetProperties(BindingFlags.Instance | BindingFlags.Public)
      .Where(prop => prop.CanRead && prop.CanWrite)
      .Where(prop => !prop.GetIndexParameters().Any())
      .Where(prop => allowedTypes.Contains(prop.PropertyType))
   // .Where(prop => ...) // Add here more coditions if required
      .ToArray();

    File.WriteAllLines(fileName, source
      .Select(item => string.Join(",", properties
        .Select(property => property.GetValue(item))))); 
  } 

然后使用它:

  List<Car> cars = new List<Car>();

  ... 

  SaveToFile(Cars, @"D:\WriteLines.txt");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多