Apparently you expect your AccountNumbers to contain characters that are not digits, and you don't want to consider them. You want AccountNumbers that contain only digits.
To prevent to remove the digits more than once per AccountNumber, my advice would be to use an extra Select for this.
After removing the non-characters, consider to convert the AccountNumber to an int, this would speed up your processing considerably. If you don't want to convert it to int, remove the Parse part.
Another advice for this: Never let your LINQ statements return NULL. The result of your LINQ statements (as long as it returns IEnumerable<...>
) represents a sequence of similar items. If there are no items in the sequence, return an empty sequence. This has the advantage that you don't have to check if the input is null.
List<MyRecord> myList = ...
var records = myList ?? Enumerable.Empty<MyRecord>();
ver groupedList = records.Select(record => new
{
// Remove the non-digits, and parse to Int32 or Int64
// I'm certain that this parses, because it is digits only (or out-of-range?)
AccountNumber = Int32.Parse(record.AccountNumber.Where(c => Char.IsDigit(c))),
Debt = record.TotalDebt, // are you sure this property is also called TotalDebt?
})
// Now the GroupBy is easy and efficient:
.GroupBy(record => record.AccountNumber,
(accountNumber, recordsWithThisAccountNumber) => new
{
AccountNumber = accountNumber,
TotalDebt = recordsWithThisAccountNumber.Sum()
});
Now you can be certain that groupedList is a non-null sequence. If myList was null, then groupedList is an empty sequence.