gpt4 book ai didi

c# - 根据c#中的文件大小将文件列表拆分为多个较小的列表

转载 作者:行者123 更新时间:2023-11-30 17:43:02 25 4
gpt4 key购买 nike

我正在编写一个方法,该方法将获取大量文件并将它们拆分为较小的列表,这些列表包含的磁盘空间总量相等。例如。一个包含 1 个 100kb 文件的列表,另一个包含 100 个 1kb 文件的列表。

我的代码执行以下操作。如果列表中的所有文件总计超过 500kb,我想将此列表拆分为更小的列表。这意味着如果我的总计数为 600kb,我将有 2 个列表。我想向每个列表中添加 300kb(或尽可能接近)的文件。

我编写的代码可以很好地做到这一点,但有一种常见的情况会把它搞砸。如果我有 99 个文件。 99 个是 1kb,最后一个文件是 400kb。此代码将向每个列表来回添加 1 个文件,直到两个列表都有 49 个文件,每个列表中有 49kb,但现在最终的文件很大,这意味着 1 个列表为 49kb,另一个为 449kb。我需要一种巧妙的方法来划分文件,以便 400kb 的文件最终单独出现在列表中。

int listcount = (int)Math.Ceiling(totalsize / listlimit); //500kb

List<string>[] lists = new List<string>[listcount];
double[] memorytotals = new double[listcount]; // this array will keep track of what the file size total is in each of the arrays.

foreach(string file in filelist)
{
double size = new FileInfo(file).Length;

int pos = 0;
for (int i = 0; i < memorytotals.Length; i++)
{
if (memorytotals[i] < memorytotals[pos]) { pos = i; }
}
if(size > memorytotals[pos])
{
//get the next smallest array that is not pos
int pos2 = 0;
for (int i = 0; i < memorytotals.Length; i++)
{
if (memorytotals[i] < memorytotals[pos2] && pos2 != pos)
{
pos2 = i;
}
}

//if moving all contents of the smallest array into the second smallest array make for a smaller size than just putting the larger file directly into the smaller array than do it.
double newlistTotal = memorytotals[pos] + memorytotals[pos2];
if(newlistTotal < size)
{
lists[pos2].AddRange(lists[pos]);
//empty the list in order to add the new larger file to this list.
lists[pos].Clear();
}
}
lists[pos].Add(file);
}

最佳答案

这不是最佳解决方案,但至少它将文件拆分为大小相同的不同列表。在代码中可以做很多改进,这只是第一种方法。

我根据文件的大小对文件进行排序,然后我开始将它们添加到列表中,检查是否没有超过限制。

int listcount = (int)Math.Ceiling(totalsize / listlimit); //500kb
List<FileInfo> fileInfoList = new List<FileInfo>();

List<string>[] lists = new List<string>[listcount];

double[] memorytotals = new double[listcount]; // this array will keep track of what the file size total is in each of the arrays.

foreach (string file in filelist)
{
fileInfoList.Add(new FileInfo(file)); // Add all the FileInfo to a list to order it
}

fileInfoList.OrderBy(r => r.Length);


foreach (FileInfo fileInfo in fileInfoList)
{
double size = fileInfo.Length;

// flag for only add a file one time
bool flag = true;


for (int j = 0; j < memorytotals.Length; j++)
{

// check if the file fits in the list
if (memorytotals[j] + size < listcount && flag)
{
memorytotals[j] = memorytotals[j] + size;
lists[j].Add(fileInfo.FullName);
flag = false;
}
}
}

关于c# - 根据c#中的文件大小将文件列表拆分为多个较小的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31456650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com