Search code examples
c#listlinqcasting

LINQ var type cast to List


I've got a method grouping given List with LINQ. I want to output the grouped list with other class. What is the proper way to cast type?

Method:

 public List<OutMyFileData> GetGroupedFiles(string path)
{
    // List of all files in given path
    List<MyFileData> allFiles = GetFiles(path);

    return allFiles.OrderBy(file => file.Extension)
                .GroupBy(file => file.Extension)
                .Select(file => new
                {
                    type = file.Key,
                    files = file.Select(ofile => new
                    {
                        ofile.Name,
                        ofile.LastMod,
                        ofile.Size
                    })
                }).ToList() as List<OutMyFileData>;
}

And classes:

public class MyFileData
{
public string Name { get; set; }

public string LastMod { get; set; }

public long Size { get; set; }

public string Extension { get; set; }
}


public class OutMyFileData
{
public string Name { get; set; }

public string LastMod { get; set; }

public long Size { get; set; }

}

Solution

  • First, you might not return an anonymous object as your result because the type can't be declared for the return type of method.

    If I understand correctly, you can try to write a class as return ViewModel MyFileViewModel which can contain your return values.

    public class MyFileViewModel{
        public string Type { get; set; }
        public IEnumerable<OutMyFileData> Files { get; set; }
    }
                    
    public class OutMyFileData
    {
        public string Name { get; set; }
    
        public string LastMod { get; set; }
    
        public long Size { get; set; }
    }
    

    Then you can call as below

    public List<MyFileViewModel> GetGroupedFiles(string path)
    {
        List<MyFileData> allFiles = GetFiles(path);
    
        return allFiles.GroupBy(file => file.Extension)
            .Select(file => new MyFileViewModel()
            {
                Type = file.Key,
                Files = file.Select(ofile => new OutMyFileData()
                {
                    Name = ofile.Name,
                    LastMod = ofile.LastMod,
                    Size = ofile.Size
                })
            }).ToList();
    }