【发布时间】:2009-07-01 05:02:07
【问题描述】:
小问题:如何修改List 中的单个项目? (或更准确地说,struct 的成员存储在 List 中?)
完整解释:
首先,下面使用的struct 定义:
public struct itemInfo
{
...(Strings, Chars, boring)...
public String nameStr;
...(you get the idea, nothing fancy)...
public String subNum; //BTW this is the element I'm trying to sort on
}
public struct slotInfo
{
public Char catID;
public String sortName;
public Bitmap mainIcon;
public IList<itemInfo> subItems;
}
public struct catInfo
{
public Char catID;
public String catDesc;
public IList<slotInfo> items;
public int numItems;
}
catInfo[] gAllCats = new catInfo[31];
gAllCats 在加载时填充,并在程序运行时依次类推。
当我想对subItems 数组中的itemInfo 对象进行排序时,就会出现问题。
我正在使用 LINQ 来执行此操作(因为似乎没有任何其他合理的方法可以对非内置类型的列表进行排序)。
所以这就是我所拥有的:
foreach (slotInfo sInf in gAllCats[c].items)
{
var sortedSubItems =
from itemInfo iInf in sInf.subItems
orderby iInf.subNum ascending
select iInf;
IList<itemInfo> sortedSubTemp = new List<itemInfo();
foreach (itemInfo iInf in sortedSubItems)
{
sortedSubTemp.Add(iInf);
}
sInf.subItems.Clear();
sInf.subItems = sortedSubTemp; // ERROR: see below
}
错误是,“不能修改 'sInf' 的成员,因为它是一个 'foreach 迭代变量'”。
a,这个限制没有意义;这不是 foreach 构造的主要用途吗?
b,(也是出于恶意)如果不修改列表,Clear() 会做什么? (顺便说一句,根据调试器,如果我删除最后一行并运行它,列表确实会被清除。)
所以我尝试采用不同的方法,看看它是否可以使用常规的 for 循环。 (显然,这只是允许的,因为 gAllCats[c].items 实际上是 IList;我认为它不允许您以这种方式索引常规的 List。)
for (int s = 0; s < gAllCats[c].items.Count; s++)
{
var sortedSubItems =
from itemInfo iInf in gAllCats[c].items[s].subItems
orderby iInf.subNum ascending
select iInf;
IList<itemInfo> sortedSubTemp = new List<itemInfo>();
foreach (itemInfo iInf in sortedSubItems)
{
sortedSubTemp.Add(iInf);
}
//NOTE: the following two lines were incorrect in the original post
gAllCats[c].items[s].subItems.Clear();
gAllCats[c].items[s].subItems = sortedSubTemp; // ERROR: see below
}
这一次,错误是,“无法修改'System.Collections.Generic.IList.this[int]'的返回值,因为它不是一个变量。”啊!如果不是变量,它是什么?什么时候变成了“返回值”?
我知道必须有一个“正确”的方法来做到这一点;我是从 C 背景开始的,我知道我可以在 C 中做到这一点(尽管有很多手动内存管理。)
我四处搜索,似乎ArrayList 已经过时,支持泛型类型(我使用的是 3.0),我不能使用数组,因为大小需要是动态的。
【问题讨论】: