gdoron
gdoron

Reputation: 150253

string.Join throws OutOfMemory Exception

I have a list of strings and I want to join them with " "(space) between them, so I use the string.Join method:

foreach (var line in lines)
{        
    var strings = lines.Where(l => l.Code == line.Code).Select(l => l.Data);
    var original = string.Join(" ", strings);        
}

Data looks something like this: "123456789, 987654321, 32132, 7873892 ..."

But I get an OutOfMemoryException. Why? each string is approximatly 100-150 characters and there are 5-10 strings in the list.

Is there a better way then the string.Join?

Upvotes: 2

Views: 1718

Answers (3)

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

foreach (var line in lines.GroupBy(p=>p.Code))
{        
    var original = string.Join(" ", line.Select(p=>p.Data));        
}

Upvotes: 2

Magnus
Magnus

Reputation: 46909

Try this (and let us know if you get the same error):

lines.GroupBy(l => l.Code).Select(l => string.Join(" ", l.Select (x => x.Data)));

Upvotes: 4

user1231231412
user1231231412

Reputation: 1659

The StringBuild() class can join strings and isn't immutable.

Here's an MSDN article talking about immutable string vs how StringBuilder works. http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx

Upvotes: -1

Related Questions