簡短問題:如何修改List
中的單個項目? (或者更準確地說,一個struct
成員存儲在List
?)c#修改列表中的結構<T>
完整的解釋:
首先,下面所使用的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),並且我不能使用數組,因爲大小需要是動態的。
太棒了,有效。非常感謝! – andersop 2009-07-01 06:01:57
感謝您指出了這一點。就修改struct屬性的屬性而言,我知道這一點,但我不知道它應用於泛型集合。我只是假定List本身就是一個類,所以它的索引器會返回一個對結構體的引用。我想象它是如何與非泛型集合一起工作的。再次感謝 – LoveMeSomeCode 2009-10-26 16:31:21