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");