c# modifying structs in a List

后端 未结 5 774
天涯浪人
天涯浪人 2021-01-01 19:57

Short question: How can I modify individual items in a List? (or more precisely, members of a struct stored in a List?)

Full e

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 20:14

    The two errors you specified have to do with the fact that you are using structs, which in C# are value types, not reference types.

    You absolutely can use reference types in foreach loops. If you change your structs to classes, you can simply do this:

        foreach(var item in gAllCats[c].items)
        {
            item.subItems = item.subItems.OrderBy(x => x.subNum).ToList();
        }
    

    With structs this would need to change to:

        for(int i=0; i< gAllCats[c].items.Count; i++)
        {
            var newitem = gAllCats[c].items[i];
            newitem.subItems = newitem.subItems.OrderBy(x => x.subNum).ToList();
            gAllCats[c].items[i] = newitem;
        }
    

    The other answers have better information on why structs work different than classes, but I thought I could help with the sorting part.

提交回复
热议问题