System.InvalidOperationException: Sequence contains no elements
System.InvalidOperationException: Collection was modified; enumeration operation may not proceed.
You’re performing an operation that isn’t valid given the current state of the object.
Fix 1: Sequence Contains No Elements
// ❌ .First() on empty collection
var item = list.First(); // 💥 If list is empty
// ✅ Use FirstOrDefault
var item = list.FirstOrDefault();
if (item == null) { /* handle empty */ }
// ✅ Or check first
if (list.Any()) {
var item = list.First();
}
Fix 2: Modifying Collection During Iteration
// ❌ Removing items while iterating
foreach (var item in list) {
if (item.IsExpired) list.Remove(item); // 💥
}
// ✅ Use RemoveAll or iterate backwards
list.RemoveAll(item => item.IsExpired);
// Or collect items to remove first
var toRemove = list.Where(x => x.IsExpired).ToList();
foreach (var item in toRemove) list.Remove(item);
Fix 3: DbContext Already Disposed
// ❌ Using DbContext after it's disposed
User user;
using (var db = new AppDbContext()) {
user = db.Users.First();
}
var name = user.Address.City; // 💥 Lazy loading after dispose
// ✅ Include related data before disposing
using (var db = new AppDbContext()) {
user = db.Users.Include(u => u.Address).First();
}
Fix 4: Nullable Value Type
// ❌ Accessing .Value on null Nullable
int? count = null;
int value = count.Value; // 💥
// ✅ Check HasValue or use default
int value = count ?? 0;
int value = count.GetValueOrDefault();
Fix 5: Cross-Thread UI Access
// ❌ Updating UI from background thread (WPF/WinForms)
Task.Run(() => {
label.Text = "Done"; // 💥
});
// ✅ Use Dispatcher/Invoke
Dispatcher.Invoke(() => label.Text = "Done");