[英]c#: how do I remove an Item inside IEnumerable
我正在制作一個接受IEnumerable作為Itemsource的自定義網格。 但是,在刪除方法期間,我無法刪除itemsource中的一個Item。 你們可以使用下面的代碼來幫助我嗎?
static void Main(string[] args)
{
List<MyData> source = new List<MyData>();
int itemsCount = 20;
for (int i = 0; i < itemsCount; i++)
{
source.Add(new MyData() { Data = "mydata" + i });
}
IEnumerable mItemsource = source;
//Remove Sample of an mItemSource
//goes here ..
}
public class MyData { public string Data { get; set; } }
你不能 IEnumerable
(及其通用的IEnumerable<T>
)僅用IEnumerable<T>
目的-枚舉某些集合的內容。 它不提供修改集合的功能。
如果您正在尋找一個提供所有典型方法來修改集合的接口(例如,添加,刪除),那么如果需要按索引訪問元素,請查看ICollection<T>
或IList<T>
。
或者,如果您的目標是為某些內容提供IEnumerable
,但刪除了某些項目,請考慮使用Enumerable.Except()
過濾掉它們( 如枚舉 )。
使用while循環在刪除時遍歷列表。
int i = 0;
while(i < source.Count){
if(canBeRemoved(source[i])){
source.RemoveAt(i);
}else{
i++;
}
}
我能夠使用動態從Itemsource中刪除Item
static void Main(string[] args)
{
List<MyData> source = new List<MyData>();
int itemsCount = 20;
for (int i = 0; i < itemsCount; i++)
{
source.Add(new MyData() { Data = "mydata" + i });
}
IEnumerable mItemsource = source;
//Remove Sample of an mItemSource
dynamic d = mItemsource;
d.RemoveAt(0);
//check data
string s = source[0].Data;
}
public class MyData { public string Data { get; set; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.