Creating Key / Value Collections Using LINQ To Objects

I am trying to use LINQ To Objects to create a query that will give me files indexed by file name, matching values ​​with their binary data like byte[].

However, I cannot find a "neat" way to do this. I hope to get something like output Dictionary<T,K>.

Here is what I still have. Example delimFileNames = "1.jpg | 2.jpg"

//Extract filenames from filename string
//and read file binary from file
//select result into a filename indexed collection
var result = from f in delimFileNames.Split(Constants.DDS_FILENAME_SEPARATOR)
            let filePath = Path.Combine(ddsClient.WorkingDirectory, f)
            let fileData = File.ReadAllBytes(filePath)
            select new KeyValuePair<string, byte[]>(f, fileData);

return result.ToDictionary(kvp => kvp.Key, kvp=> kvp.Value);

The main scraper for the head is why I can't use bottomless ToDictionary () or live translation. Any suggestions or alternatives to improve the above are appreciated.

+3
source share
3 answers

ToDictionary() KeyValuePair - , :

public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(
     IEnumerable<KeyValuePair<TKey, TValue>> source)
{
    return source.ToDictionary(kvp => kvp.Key, kvp=> kvp.Value);
}

:

var result = from f in delimFileNames.Split(Constants.DDS_FILENAME_SEPARATOR)
                                     .ToDictionary(f => f,
          // Outdented to avoid scrolling
          f => File.ReadAllBytes(Path.Combine(ddsClient.WorkingDirectory, f));

"let", select , ( ) .

+5

" - , ToDictionary() [...]"

ToDictionary , . Microsoft , , , . , .

"[...] .

Linq IEnumerable<KeyValuePair<TKey, TValue>>, Dictionary<TKey, TValue>. /, .

, Dictionary<TKey, TValue> IS a IEnumerable<KeyValuePair<TKey, TValue>> ( ), , / , Linq, - , .

+2

KeyValuePair<,>, , , Key Value:

var files =
    from fileName in delimFileNames.Split(Constants.DDS_FILENAME_SEPARATOR)
    let filePath = Path.Combine(ddsClient.WorkingDirectory, fileName)
    select new
    {
        Path = filePath,
        Data = File.ReadAllBytes(filePath)
    };

return files.ToDictionary(file => file.Path, file => file.Data);
+1

Source: https://habr.com/ru/post/1717351/


All Articles