删除列表数据foreach

时间:2014-02-05 08:15:05

标签: c# foreach

嗨我有这样的代码

List<CQuizOccurrence> matchData = new List<CQuizOccurrence>();
foreach (CQuizOccurrence myQuizOccurrence in Global.quizOccurrences) 
{
    DateTime dtDatabase = (DateTime)myQuizOccurrence.occurred;
    string dt = dtDatabase.ToString();
    if (dt == dateOccur) {
        matchData.Add(myQuizOccurrence);
    }
}

foreach (CQuizOccurrence myQuizOccurrence in matchData)
{
    Global.quizOccurrences.RemoveAt(0);
}

我认为该代码将能够 删除'global = quizOccurences'数据'dt == dateOccur' ,但我错了,它只是简单地删除' Global.quizOccurences',索引为0

如何按照我的意愿纠正它(斜体和粗体文字)

2 个答案:

答案 0 :(得分:3)

RemoveAt()删除指定索引处的项目。在您的情况下,您需要删除符合特定条件的项目,而不是列表开头的项目。

var itemsToRemove = Global.quizOccurrences
    .Where(q => q.occurred.ToString() == dateOccur)
    .ToList();

foreach(var quizOccurrence in itemsToRemove)
{
    Global.quizOccurrences.Remove(quizOccurrence);
}

答案 1 :(得分:1)

尝试更改此行:

Global.quizOccurrences.RemoveAt(0);

到此:

Global.quizOccurrences.Remove(myQuizOccurrence);