Reputation: 19831
I'm having some legacy code that recieves a string[,]
as one of the method arguments.
However, in my method I recieve a IDictionary<string, string>
that I have to convert to a string[,]
to proceed.
I've created the code like that,
var names = attachments.Keys.ToArray();
var paths = attachments.Values.ToArray();
var multipleAttachments = new string[2,attachments.Count];
for(var i = 0; i < attachments.Count; i++)
{
multipleAttachments[0, i] = names[i];
multipleAttachments[1, i] = paths[i];
}
I'm not really happy with it and I am looking for some way to use a LINQ expression for the convertion. Is that possible?
Upvotes: 0
Views: 152
Reputation: 1502446
LINQ isn't particularly good when it comes to rectangular arrays. You can easily create a jagged array:
// Note that this ends up "rotated" compared with the rectangular array
// in your question.
var array = attachments.Select(pair => new[] { pair.Key, pair.Value })
.ToArray();
... but there's no equivalent for rectangular arrays. If you have to use a rectangular array, you might want to consider creating an extension method to perform the conversion for you. If you only want it for this case, you're probably best off sticking with what you've got... or possibly:
var multipleAttachments = new string[2, attachments.Count];
int index = 0;
foreach (var pair in multipleAttachments)
{
multipleAttachments[0, index] = pair.Key;
multipleAttachments[1, index] = pair.Value;
index++;
}
That will avoid creating the extra arrays, and will also not rely on Keys
and Values
supplying their entries in the same order.
Upvotes: 5
Reputation: 14929
var multipleAttachments = new string[2, attachments.Count];
int i = 0;
attachments.ToList().ForEach(p =>
{
multipleAttachments[0, i] = p.Key;
multipleAttachments[1, i] = p.Value;
i++;
});
Upvotes: 2