Home > Enterprise >  LINQ Query - Custom Output, Group Headers
LINQ Query - Custom Output, Group Headers

Time:03-30

I'm trying to get an custom output using LINQ, I've made custom class to store data:

public class MyFileData
{
// File Name
public string Name { get; set; }
// File's last modification date
public string LastMod { get; set; }
// File size
public long Size { get; set; }
// File extension
public string FileType { get; set; }
}

Desired output should look like this:

{
    "name": "codeblocks-20.03mingw-setup.exe",
    "lastMod": "13.03.2022 22:57:47",
    "size": 152419674,
},
{
    "name": "somefile.png",
    "lastMod": "16.01.2022 13:16:06",
    "size": 82973864,
},

so excluding one of the class properties. Also I would like to add group headers based on file extensions, so sth looking like this:

"type": ".exe",
"files": [
{
    "name": "codeblocks-20.03mingw-setup.exe",
    "lastMod": "13.03.2022 22:57:47",
    "size": 152419674,
    "fileType": ".exe"
},
{
    "name": "DiscordSetup.exe",
    "lastMod": "16.01.2022 13:16:06",
    "size": 82973864,
    "fileType": ".exe"
},
...
]

But currently I'm able to return just the list of the class elements, output looks like this:

[
{
    "name": null,
    "lastMod": null,
    "size": 0,
    "fileType": ".exe"
},
{
    "name": "setup_becastled_0.2.14_(64bit)_(50823).exe",
    "lastMod": "13.01.2022 13:00:33",
    "size": 281792488,
    "fileType": ".exe"
},
{
    "name": "basic-miktex-21.12-x64.exe",
    "lastMod": "12.01.2022 23:20:32",
    "size": 136437512,
    "fileType": ".exe"
}]

the class method returns:

 List<MyFileData> list = new(MyFileData){*method getting files*}
 return list;

and if grouped:

 foreach(string fileExtension in fileExtensions)
    {
        IEnumerable<MyFileData> query =
             from file in allFiles
             where file.FileType == fileExtension
             select file;

        sortedFiles.Add(new MyFileData{
            FileType = fileExtension });
        sortedFiles.AddRange(query.ToList());
    }
        
    return sortedFiles;

I need a hint how to make custom output with LINQ

CodePudding user response:

You could use the GroupBy() method (see docs).

Assuming you have this:

var myFileDatas = new List<MyFileData>
{
    new MyFileData { Name = "codeblocks-20.03mingw-setup.exe", FileType = ".exe", LastMod = "13.03.2022 22:57:47", Size = 152419674 },
    new MyFileData { Name = "DiscordSetup.exe", FileType = ".exe", LastMod = "16.01.2022 13:16:06", Size = 82973864 },
    new MyFileData { Name = "Abc.zip", FileType = ".zip", LastMod = "01.01.2022 13:16:06", Size = 82973864 }
};

...the following line results in two groups.

var result = myFileDatas.GroupBy(x => x.FileType);

The group with key ".zip" has 1 entry and the group with ".exe" has two entries.

  • Related