如何在List <t> .RemoveAll方法中删除Nothing时抛出异常?

时间:2015-05-24 22:56:41

标签: c# list

我有以下代码行:

races.RemoveAll(br => RaceID == br.raceID);

这是为了删除Race List中符合此条件的所有种族(具有相同的RaceID),并且这行代码有效。

但是,我的问题是,如果删除NOTHING,如何抛出异常?

我想这样做:

 if (nothing is removed)
{
throw new Exception ("Nothing was removed from the list, check input");
}

1 个答案:

答案 0 :(得分:8)

RemoveAll返回int值 - 调用删除的元素数。

var elementsRemoved = races.RemoveAll(br => RaceID == br.raceID);
if (elementsRemoved == 0)
{
    throw new Exception ("Nothing was removed from the list, check input");
}