[c#] Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

When using LINQ to get data from a list I encounter this error. How can this be fixed?

Value cannot be null. Parameter name: source

var nCounts = from sale in sal
              select new
              {
                  SaleID = sale.OrderID,
                  LineItem = from sli in sale.LineItems
                             group sli by sli.Item into ItemGroup
                             select new
                             {
                                 Item = ItemGroup.Key,
                                 Weeks = ItemGroup.Select(s => s.Week)
                             }
              };

foreach (var item in nCounts)
{
    foreach (var itmss in item.LineItem)
    {
        // MessageBox.Show(itmss.Item.Name);
        itemsal.Add(new Roundsman.BAL.WeeklyStockList(itmss.Item.Name.ToString(),
                    itmss.Item.Code.ToString(),
                    itmss.Item.Description.ToString(),
                    Convert.ToInt32(itmss.Item.Quantity), 2, 2, 2, 2, 2, 2, 2, 2, 2));
    }                      
}

Error which i got after execution my LINQ I got that type of result (one line, orginally):

System.Linq.Enumerable.WhereSelectListIterator<Roundsman.BAL.Sale, <>f__AnonymousType1<int,System.Collections.Generic.IEnumerable <<>f__AnonymousType0<Roundsman.BAL.Items.Item,System.Collections.Generic.IEnumerable <Roundsman.BAL.WeeklyRecord>>>>>

This question is related to c# linq

The answer is


This error can occur in several places, most commonly running further LINQ queries on top of a null collection. LINQ as Query Syntax can appear more null-safe than it is. Consider the following samples:

var filteredCollection = from item in getMyCollection()
                         orderby item.ReportDate
                         select item;

This code is not NULL SAFE, meaning that if getMyCollection() returns a null, you'll get the Value cannot be null. Parameter name: source error. Very annoying! But it makes perfect sense because LINQ Query syntax is just syntactic sugar for this equivalent code:

var filteredCollection = getMyCollection().OrderBy(x => x.ReportDate);

Which obviously will blow up if the starting method returns a null.

To prevent this, you can use a null coalescing operator in your LINQ query like so:

var filteredCollection = from item in getMyCollection() ?? 
                              Enumerable.Empty<CollectionItemClass>()
                         orderby item.ReportDate
                         select item;

However, you'll have to remember to do this in any related queries. The best approach (if you control the code that generates the collection) is to make it a coding practice to NEVER RETURN A NULL COLLECTION, EVER. In some cases, returning a null object from a method like "getCustomerById(string id)" is fine, depending on your team coding style, but if you have a method that returns a collection of business objects, like "getAllcustomers()" then it should NEVER return a null array/enumerable/etc. Always always always use an if check, the null coalescing operator, or some other switch to return an empty array/list/enumerable etc, so that consumers of your method can freely LINQ over the results.


This exception could point to the LINQ parameter that is named source:

 System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)

As the source parameter in your LINQ query (var nCounts = from sale in sal) is 'sal', I suppose the list named 'sal' might be null.


I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.

For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.

Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.


Ok - my case was not strictly related to this question, but I ended up on this page when Googling for the same exception; I queried an SQL database with LINQ when I got this exception.

private Table<SubscriptionModel> m_subscriptionsSql;
var query = from SubscriptionModel subscription in m_subscriptionsSql ...

Turned out I forgot to initialize my Table instance variable, that I used in the LINQ query.

m_subscriptionsSql = GetTable<SubscriptionModel>();

Here are more code examples that will produce the argument null exception:

List<Myobj> myList = null;
//from this point on, any linq statement you perform on myList will throw an argument null exception
myList.ToList();
myList.GroupBy(m => m.Id);
myList.Count();
myList.Where(m => m.Id == 0);
myList.Select(m => m.Id == 0);
//etc...