简短问题:如何修改 List
中的单个项目?(或者更准确地说,如何修改存储在 List
中的 struct
成员?)
完整解释:
首先,下面使用的 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
}
错误为“Cannot modify members of 'sInf' because it is a 'foreach iteration variable'”。
a、这个限制没有意义;这不是foreach结构的主要用途吗?
b、(还出于怨恨)如果不修改列表,Clear()做了什么呢?(顺便说一下,如果我删除最后一行并运行它,List确实被清空了,根据调试器的显示。)
因此,我尝试采用不同的方法,并查看是否可以使用常规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
}
这次出现的错误是"Cannot modify the return value of 'System.Collections.Generic.IList.this[int]' because it is not a variable."糟糕!它既不是变量,又什么呢?何时变成了'返回值'?
我知道一定有一种“正确”的方法来处理这个问题;我是从C背景下来的,我知道我可以在C中完成它(尽管需要进行大量手动内存管理)。
我搜索了一下,看起来ArrayList
已经过时了,被泛型类型取代了(我使用的是3.0),而且我不能使用数组,因为大小需要是动态的。