c#修改List <T>中的结构

and*_*sop 15 c# arrays foreach

简短问题:如何修改单个项目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];
Run Code Online (Sandbox Code Playgroud)

gAllCats 在加载时填充,在程序运行时依此类推.

当我想要对数组中的itemInfo对象进行排序时,会出现问题subItems.我正在使用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
}
Run Code Online (Sandbox Code Playgroud)

错误是"无法修改'sInf'的成员,因为它是'foreach迭代变量'".

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
}
Run Code Online (Sandbox Code Playgroud)

这一次,错误是"无法修改'System.Collections.Generic.IList.this [int]'的返回值,因为它不是变量." 啊! 它是什么,如果不是变量?什么时候它成为'回归价值'?

我知道必须有一个'正确'的方法来做到这一点; 我是从C背景来看这个,我知道我可以在C中做到这一点(尽管有一些手动内存管理.)

我四处搜索,似乎ArrayList已经过时了,支持泛型类型(我使用3.0),因为大小需要动态,我不能使用数组.

Fre*_*örk 14

查看for循环方法,在编译错误文档中给出了原因(和解决方案):

尝试修改由中间表达式生成但未存储在变量中的值类型.当您尝试直接修改泛型集合中的结构时,可能会发生此错误.

要修改结构,首先将其分配给局部变量,修改变量,然后将变量分配回集合中的项目.

因此,在for循环中,更改以下行:

catSlots[s].subItems.Clear();
catSlots[s].subItems = sortedSubTemp;   // ERROR: see below
Run Code Online (Sandbox Code Playgroud)

...到:

slotInfo tempSlot = gAllCats[0].items[s];
tempSlot.subItems  = sortedSubTemp;
gAllCats[0].items[s] = tempSlot;
Run Code Online (Sandbox Code Playgroud)

我删除了对该Clear方法的调用,因为我认为它不会添加任何内容.