tags:

views:

188

answers:

3

I am having a info class with following field like id,name,address and i have created list of that info like List.

I want to have all the values of list into comma seperated strings using linq. Is there any way for this.

A: 

Have a look at this example by Mike Hadlow. It needs some improvement (escaping commas, new line support etc) but gives you the basic idea.

RichardOD
A: 

Taken from the LinQExtensions.cs found at 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;

    }
Mathlec
A: 

simple way... may not be the fastest so it depends on how many records you are processing

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