I have the following Linq to SQL:
var finalResults =
(from d in data
group d by new { d.LocationName, d.Year, d.Month, d.Denominator, d.Numerator } into groupItem
orderby groupItem.Key.Year, groupItem.Key.Month, groupItem.Key.LocationName
select new
{
IndicatorName = IndicatorName,
groupItem.Key.LocationName,
Year = string.Format("{0}", (int?)groupItem.Key.Year),
Month = string.Format("{0:00}", (int?)groupItem.Key.Month)
Numerator = groupItem.Sum(x => x.Numerator),
groupItem.Key.Denominator,
}).ToList();
The problem is that there are some empty strings in both the Year and Month. When this happens, I want to replace the empty string with a “Not Available”. I tried doing a ternary statement like this:
Year = string.Format("{0}", (int?)groupItem.Key.Year) == "" ? "Not Available" : string.Format("{0}", (int?)groupItem.Key.Year),
Month = string.Format("{0:00}", (int?)groupItem.Key.Month) == "" ? "Not Available" : string.Format("{0:00}", (int?)groupItem.Key.Month),
What I was trying to do was “if Year (or Month) has an empty string, display “Not Available” otherwise display the value
However, this does not do what I though it would do because I still fail my
Assert.AreNotEqual(“”, endItem.Year);
Assert.AreNotEqual(“”, endItem.Month);
tests.
Any advice?
I would strongly recommend doing the final manipulation in LINQ to Objects instead. Project all the bits you need in LINQ to SQL, then use
AsEnumerableto get back to LINQ to Objects:It’s much easier to reason about what’s going to happen in complicated scenarios when you’re using LINQ to Objects – you don’t need to worry about differences in null handling etc.