Royi Namir
Royi Namir

Reputation: 148544

linq ToArray<string>().Join(...) method is not working?

I have a datatble with one column

I want to concat each filename with wrapper div

something like :

    <div>File Attached : file1 </div>
    <div>File Attached : file2 </div>
    <div>File Attached : file3 </div>
...

I have succedded with :

 string f = String.Join(" ", (from dr in dt.AsEnumerable()
                                                 select "<div>File Attached : " + dr[0].ToString() + "</div>").ToArray<string>());

but didnt success with :

https://i.sstatic.net/xCKLD.jpg enter image description here

How can i do it with the .Join method after the ToArray method ?

Upvotes: 1

Views: 4478

Answers (2)

Lasse Espeholt
Lasse Espeholt

Reputation: 17782

Join is not the same as String.Join as you have discovered. Enumerable.Join works like joining in databases (but still on local objects, Queryable.Join works with SQL.) An example is given here:

http://msdn.microsoft.com/en-us/library/bb534675.aspx

You could (but I don't recommend it because it will be ambiguous to the user) write an extension method like this:

public static class StringExtensions
{
    public string Join(this IEnumerable<string> source, string sep)
    {
        return string.Join(sep, source.ToArray()); // You can erase `.ToArray()` if you're using .Net 4
    }
}

and then it would work with (...).Join(" ").

My solution: (4.0)

var query = from dr in dt.AsEnumerable() // You may be able to erase `AsEnumerable` depending on your source
            select "<div>File Attached : " + dr[0] + "</div>";
var f = string.Join(" ", query);

My solution: (3.5)

var arr = dt.AsEnumerable()
            .Select(dr => "<div>File Attached : " + dr[0] + "</div>")
            .ToArray();
var f = string.Join(" ", arr);

Upvotes: 2

A. Tapper
A. Tapper

Reputation: 1271

Are you sure that that the Join function is the correct one? It sounds like you could be using the Aggregate function to end up with the same result, like this:

dt.AsEnumerable().Aggregate(string.Empty, (x,y) => x + string.Format("<div>File Attached : {0} </div>", y));

Upvotes: 1

Related Questions