代码之家  ›  专栏  ›  技术社区  ›  Jalpesh Vadgama

使用linq转换逗号分隔列表中的列表?

  •  0
  • Jalpesh Vadgama  · 技术社区  · 15 年前

    我有一个信息类,有如下字段,如id、姓名、地址,我已经创建了类似信息列表的列表。

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

    3 回复  |  直到 14 年前
        1
  •  0
  •   Matthew Whited    15 年前

    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
  •  0
  •   RichardOD    15 年前

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

        3
  •  0
  •   Mathlec    15 年前

    Batch Updates and Deletes with LINQ to SQL

    /// <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;
    
        }