1

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?

michasaucer
  • 4,562
  • 9
  • 40
  • 91

2 Answers2

2

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

input.GroupBy(x => x.Extension).ToDictionary(y => y.Key, y => y.AsEnumerable());
1
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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks for your answer. Its really helpful to understand `IGrouping` but i want to have a dictionary ut thanks anyway! – michasaucer Apr 11 '20 at 09:14
  • 1
    @michasaucer then like I said: use `ToLookup`, which functions *like* a dictionary, except it is intended for key=>multiple (rather than key=>single, which is what dictionary does) – Marc Gravell Apr 11 '20 at 10:51