【问题标题】:Converting List in Comma Separated List with linq?用linq转换逗号分隔列表中的列表?
【发布时间】:2009-10-07 13:18:53
【问题描述】:

我有一个带有以下字段的信息类,例如 id、名称、地址,并且我创建了该信息的列表,例如 List。

我想使用 linq 将列表的所有值转换为逗号分隔的字符串。有什么办法吗?

【问题讨论】:

标签: asp.net linq csv


【解决方案1】:

简单的方法...可能不是最快的,所以这取决于您正在处理的记录数

var myObjects = new[] {
    new {
        id=1,
        name="Matt",
        address="1234 no chance ln\r\nnowhere, OH  12345"
    },
    new {
        id=1,
        name="Jim",
        address="4321 no chance ln\r\nnowhere, OH  12345"
    }
};

var myList = (from o in myObjects
              select string.Format("{0},\"{1}\",\"{2}\"",
                 o.id,
                 o.name,
                 (o.address ?? string.Empty).Replace("\r\n", ";")
                 )).ToList();

【讨论】:

    【解决方案2】:

    看看这个example by Mike Hadlow。它需要一些改进(转义逗号、新行支持等),但为您提供了基本概念。

    【讨论】:

      【解决方案3】:

      取自 Batch Updates and Deletes with LINQ to SQL 的 LinQExtensions.cs

      /// <summary>
          /// Creates a *.csv file from an IQueryable query, dumping out the 'simple' properties/fields.
          /// </summary>
          /// <param name="query">Represents a SELECT query to execute.</param>
          /// <param name="fileName">The name of the file to create.</param>
          /// <remarks>
          /// <para>If the file specified by <paramref name="fileName"/> exists, it will be deleted.</para>
          /// <para>If the <paramref name="query"/> contains any properties that are entity sets (i.e. rows from a FK relationship) the values will not be dumped to the file.</para>
          /// <para>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</para>
          /// </remarks>
          public static void DumpCSV(this IQueryable query, string fileName)
          {
              query.DumpCSV(fileName, true);
          }
      
          /// <summary>
          /// Creates a *.csv file from an IQueryable query, dumping out the 'simple' properties/fields.
          /// </summary>
          /// <param name="query">Represents a SELECT query to execute.</param>
          /// <param name="fileName">The name of the file to create.</param>
          /// <param name="deleteFile">Whether or not to delete the file specified by <paramref name="fileName"/> if it exists.</param>
          /// <remarks>
          /// <para>If the <paramref name="query"/> contains any properties that are entity sets (i.e. rows from a FK relationship) the values will not be dumped to the file.</para>
          /// <para>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</para>
          /// </remarks>
          public static void DumpCSV(this IQueryable query, string fileName, bool deleteFile)
          {
              if (File.Exists(fileName) && deleteFile)
              {
                  File.Delete(fileName);
              }
      
              using (var output = new FileStream(fileName, FileMode.CreateNew))
              {
                  using (var writer = new StreamWriter(output))
                  {
                      var firstRow = true;
      
                      PropertyInfo[] properties = null;
                      FieldInfo[] fields = null;
                      Type type = null;
                      bool typeIsAnonymous = false;
      
                      foreach (var r in query)
                      {
                          if (type == null)
                          {
                              type = r.GetType();
                              typeIsAnonymous = type.IsAnonymous();
                              properties = type.GetProperties();
                              fields = type.GetFields();
                          }
      
                          var firstCol = true;
      
                          if (typeIsAnonymous)
                          {
                              if (firstRow)
                              {
                                  foreach (var p in properties)
                                  {
                                      if (!firstCol) writer.Write(",");
                                      else { firstCol = false; }
      
                                      writer.Write(p.Name);
                                  }
                                  writer.WriteLine();
                              }
                              firstRow = false;
                              firstCol = true;
      
                              foreach (var p in properties)
                              {
                                  if (!firstCol) writer.Write(",");
                                  else { firstCol = false; }
                                  DumpValue(p.GetValue(r, null), writer);
                              }
                          }
                          else
                          {
                              if (firstRow)
                              {
                                  foreach (var p in fields)
                                  {
                                      if (!firstCol) writer.Write(",");
                                      else { firstCol = false; }
      
                                      writer.Write(p.Name);
                                  }
                                  writer.WriteLine();
                              }
                              firstRow = false;
                              firstCol = true;
      
                              foreach (var p in fields)
                              {
                                  if (!firstCol) writer.Write(",");
                                  else { firstCol = false; }
      
                                  DumpValue(p.GetValue(r), writer);
                              }
                          }
      
                          writer.WriteLine();
                      }
                  }
              }
          }
      
          private static void DumpValue(object v, StreamWriter writer)
          {
              if (v != null)
              {
                  switch (Type.GetTypeCode(v.GetType()))
                  {
                      // csv encode the value
                      case TypeCode.String:
                          string value = (string)v;
                          if (value.Contains(",") || value.Contains('"') || value.Contains("\n"))
                          {
                              value = value.Replace("\"", "\"\"");
      
                              if (value.Length > 31735)
                              {
                                  value = value.Substring(0, 31732) + "...";
                              }
                              writer.Write("\"" + value + "\"");
                          }
                          else
                          {
                              writer.Write(value);
                          }
                          break;
      
                      default: writer.Write(v); break;
                  }
              }
          }
      
          private static bool IsAnonymous(this Type type)
          {
              if (type == null)
                  throw new ArgumentNullException("type");
      
              // HACK: The only way to detect anonymous types right now.
              return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
                         && type.IsGenericType && type.Name.Contains("AnonymousType")
                         && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
                         && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        • 2011-09-29
        • 2013-07-03
        相关资源
        最近更新 更多