TrevorGoodchild TrevorGoodchild - 10 months ago 28
ASP.NET (C#) Question

Null value for anonymous types

I have a routine in C# where I pull a list of objects as such:

var data = sdfController.GetFundingSummary(CurrentUser.UserId, _companyId, "category");

Once I have that data, I need to derive a list of names from it, which I'm doing thusly:

var fundingNames =
(from names in data.AsEnumerable()
where names.FundingYear.Equals(_year.ToString())
select new { FundingName = names.FundingName }).Distinct().ToList();

and then I'm binding that list to a listview:

lvSDF.DataSource = fundingNames;

It all works great if there's data, blows up if there isn't any. I have emptyDataTemplates in place on the .aspx side to display a message if there aren't any records but I can't figure out how to initialize fundingNames to null.


The problem is that data can be null.

You need to check if this is the case before creating the LINQ query:

var fundingNames = data = null ? ...your query... : new List<string>();

Im guessing FundingName is a string here. Change accordingly if not. Also if that's the case, why are you creating an anonymous type with new { ... }? Return the string directly:

from ...
select names.FundingNames;

As PaulF correctly points out you need to do this or you'll probably get a conversion error between List<string> and List<AnonymousTypeContainingOnlyOneString>.