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

时间:2009-10-07 13:18:53

标签: asp.net linq csv

我有一个信息类,其中包含id,name,address等字段,我创建了List之类的信息列表。

我希望使用linq将list的所有值都包含在逗号分隔的字符串中。有没有办法解决这个问题。

3 个答案:

答案 0 :(得分:0)

看看这个example by Mike Hadlow。它需要一些改进(逃避逗号,新行支持等),但是给你基本的想法。

答案 1 :(得分:0)

取自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;

    }

答案 2 :(得分:0)

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

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();