michasaucer
michasaucer

Reputation: 5236

Grouping objects to dictionary by property

I Want to group Files by extensions. My FileDto looks like this:

public class FileDto
{
    public string Extension { get; set; }

    public string Filename { get; set; }
}

I want to do Dictionary (or any other collection) that will group my files by Extension (for example ".txt", ".doc") etc. I started to write some code:

// input.Files = IEnumerable<FileDto>

Dictionary<string, IEnumerable<FileDto>> dict = input.Files
    .GroupBy(x => x.Extension) // i want to Extension by my key (list of txts, list of docs etc)
    .ToDictionary(y => y.Key); // not working

foreach (var entry in dict)
{
    // do something with collection of files
}

My question is, how to group list of objects by property?

Upvotes: 1

Views: 278

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063338

var groups = input.Files
    .GroupBy(x => x.Extension)

foreach (var grp in groups)
{
    // grp.Key for the extension
    // foreach(var file in grp) for the files
}

Note ToLookup works similarly and is useful if accessing multiple times by key (you can do var grp = lookup[key];) but it is less "composable" in the LINQ-to-some-resource (database etc) sense. More here

Upvotes: 1

Dzianis Karpuk
Dzianis Karpuk

Reputation: 146

Well, you can pass second parameter and cast IGrouping to enumerable

input.GroupBy(x => x.Extension).ToDictionary(y => y.Key, y => y.AsEnumerable());

Upvotes: 2

Related Questions