我經常在我們的項目中遇到諸如「序列包含多個元素」等非信息性消息。它偶爾會發生。.Single(),.SingleOrDefault()方法的實際用法
是不是更好地檢查:
var count = collection.Count(i => predicate);
if (count > 1)
{
throw new InformativeException("...");
}
if (count == 0)
{
throw new AnotherInformativeException("...");
}
?
我真的不明白在什麼情況下Single()/ SingleOrDefault()可能會有用。只有當你將捕獲InvalidOperationException並嘗試將其轉換爲更多的信息。
當只有最多隻有一個匹配值時,單一是理想的,例如,檢查唯一標識符 - 如果列表中有兩個值具有相同的「唯一」標識符,那麼事情就會被打破,我希望Single會拋出並告訴我。 – stuartd
有關Single()等的概述,您可以查看['LINQ'文檔](http://stackoverflow.com/documentation/c%23/68/linq-queries/329/first- firstordefault-last-lastordefault-single-and-singleordefault#t = 201609071055283913178) – Nico