Reputation: 57
I am currently trying to make a method that will create a query in C# LINQ that will give me the file type, the combined size of the file type, and the total amount of files of that type. I am struggling to get multiple columns and to have the query gather the file size. It seems to only work if I get the file size separately, but still can't seem to sum them up....
This one works getting the file size alone:
var size = from f in files
select (new FileInfo(f).Length);
but does not work here and I can't get the file count either:
var all = from f in files
group Path.GetExtension(f) by Path.GetExtension(f).ToLower() into fileGroup
select new {
Ext = fileGroup,
Byt = new FileInfo(fileGroup).Length
};
EDIT:
I was able to group by type & count, but still can't figure out how to add up the file sizes by their type:
var info = files.Select(f => Path.GetExtension(f).ToLower()).GroupBy(x => x, (t, c) => new {
Extension = t,
Count = c.Count(),
Size = new FileInfo(x).Length
I am getting an error for the x
Upvotes: 0
Views: 482
Reputation: 17578
First, I'm going to recommend you rename the method parameter to filePaths
, because they are strings representing the paths. When you deal with a FileInfo
object, that's better described as a "file".
You got close with the group by, the important thing is that the select afterwards is acting on the group's data.
I'm going to write this with extension methods.
var fileDataByExtension = filePaths
.Select(fp => new FileInfo(fp))
.GroupBy(f => f.Extension)
.Select(group => new
{
Extension = group.Key,
TotalBytes = group.Sum(f => f.Length),
TotalFiles = group.Count()
});
filePaths
)FileInfo
objects up-front. It's a lot easier to extract the extension and size information from it.You now have an IEnumerable of anonymous objects.
Upvotes: 3
Reputation: 51
So "files" should be enumerable that has a count or size that contains the number of files.
var size = from f in files
select (new FileInfo(f).Length);
Upvotes: -1