为此使用 List 有什么问题?这不过是 IList 的实现,您可以自己进行分区。但如果你想透明地做到这一点:
实现 IList (它只是一个接口,没什么特别的。也许我不明白这个问题?)并通过所需大小的数组备份它。然后,您Get()
将获取index / sizeOfArrays
包含所需项目的数组的 as 索引并返回该数组中的index % sizeOfArrays
第 th 项。
为了好玩,因为这是一个懒惰的星期五,我写了一些东西。笔记:
- 我没有测试它
- 我无法评论您引用的声称这可能有助于避免内存碎片的正确性,我只是盲目地查看了您的请求
- 我不知道 List 或任何其他集合是否已经足够聪明,可以做到这一点
- 我做出了一些可能不适合您的决定(即,如果您现在使用数组,则不能盲目地将其放入代码中。
Item
例如,查看实现,尤其是 setter
也就是说,这是一个减少我周末前动机不足的起点。我给亲爱的读者(或OP)留下了一些有趣的方法作为练习.. ;-)
public class PartitionList<T> : IList<T> {
private readonly int _maxCountPerList;
private readonly IList<IList<T>> _lists;
public PartitionList(int maxCountPerList) {
_maxCountPerList = maxCountPerList;
_lists = new List<IList<T>> { new List<T>() };
}
public IEnumerator<T> GetEnumerator() {
return _lists.SelectMany(list => list).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void Add(T item) {
var lastList = _lists[_lists.Count - 1];
if (lastList.Count == _maxCountPerList) {
lastList = new List<T>();
_lists.Add(lastList);
}
lastList.Add(item);
}
public void Clear() {
while (_lists.Count > 1) _lists.RemoveAt(1);
_lists[0].Clear();
}
public bool Contains(T item) {
return _lists.Any(sublist => sublist.Contains(item));
}
public void CopyTo(T[] array, int arrayIndex) {
// Homework
throw new NotImplementedException();
}
public bool Remove(T item) {
// Evil, Linq with sideeffects
return _lists.Any(sublist => sublist.Remove(item));
}
public int Count {
get { return _lists.Sum(subList => subList.Count); }
}
public bool IsReadOnly {
get { return false; }
}
public int IndexOf(T item) {
int index = _lists.Select((subList, i) => subList.IndexOf(item) * i).Max();
return (index > -1) ? index : -1;
}
public void Insert(int index, T item) {
// Homework
throw new NotImplementedException();
}
public void RemoveAt(int index) {
// Homework
throw new NotImplementedException();
}
public T this[int index] {
get {
if (index >= _lists.Sum(subList => subList.Count)) {
throw new IndexOutOfRangeException();
}
var list = _lists[index / _maxCountPerList];
return list[index % _maxCountPerList];
}
set {
if (index >= _lists.Sum(subList => subList.Count)) {
throw new IndexOutOfRangeException();
}
var list = _lists[index / _maxCountPerList];
list[index % _maxCountPerList] = value;
}
}
}