I need to store a <string, byte[]>
pair for creating zip files (I execute an asynchronous download function that returns the byte array of the file, and I get the file name from parsing the URL)
I have been using a dictionary up to this point for testing, but I knew eventually we'd need something else, as the file names are not unique.
I'm sure I'm missing something simple, but I cannot for the life of me think of an Enumerable object collection which stores a non-unique <TValue, TValue>
pair.
Code Sample
public async Task<ZipFile> CreateZipFormUrls(List<string> urlList)
{
using (var zip = new ZipFile())
{
var files = await ReturnFileDataAsync(urlList);
foreach (var file in files)
{
var e = zip.AddEntry(file.Key, file.Value);
}
return zip;
}
}
async Task<Dictionary<string, byte[]>> ReturnFileDataAsync(IEnumerable<string> urls)
{
using (var client = new HttpClient())
{
var results = await Task.WhenAll(urls.Select(async url => new
{
Key = Path.GetFileName(url),
Value = await client.GetByteArrayAsync(url),
}));
return results.ToDictionary(x => x.Key, x => x.Value);
}
}
You could use a List<Tuple<string, byte[]>>
... or personally I'd strongly consider creating a custom class for this - and then just have a list of them.
The advantage of using a custom class over Tuple
is that you can then give the properties sensible names - and potentially add things like a method to return a Stream
for the data.
I would not use KeyValuePair
here unless the string really is meant to be a key. If the names aren't unique, they don't sound like keys to me.
See more on this question at Stackoverflow