2012-07-30 306 views
0

使用三元声明我有以下的LINQ to SQL:LinqtoSQL/C#:如何在这种情况下

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

的问题是,有两个年份和月份一些空字符串。发生这种情况时,我想用“不可用”替换空字符串。我试图做一个三元声明是这样的:

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),      

什么,我试图做的是“如果年(或月)有一个空字符串,显示‘不可用’,否则显示值

然而,这并不做什么,我虽然会做,因为我仍然不能我

Assert.AreNotEqual( “”,endItem.Year);
Assert.AreNotEqual( “”,endItem.Month);

测试。

有什么建议吗?

回答

3

我强烈建议在LINQ to Objects中做最后的操作。项目你在LINQ需要SQL的所有位,然后用AsEnumerable要回LINQ到对象:

var sqlQuery = 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, 
        groupItem.Key.LocationName, 
        groupItem.Key.Year, 
        groupItem.Key.Month, 
        Numerator = groupItem.Sum(x => x.Numerator), 
        groupItem.Key.Denominator, 
       }; 

var finalResult = sqlQuery.AsEnumerable() 
    .Select(item => new { 
       item.IndicatorName, 
       item.LocationName, 
       Year = item.Year == null ? "Not Available" 
              : item.Year.ToString(), 
       Month = item.Month == null ? "Not Available" 
              : item.Month.ToString("00"), 
       item.Numerator, 
       item.Denominator 
      }) 
    .ToList(); 

这是很容易来思考这是怎么回事,当你使用LINQ to对象在复杂的情况发生 - 你不需要担心空处理差异等

+0

这是有道理的。谢谢。 – 2012-07-30 20:44:52

0

为什么比较格式化值和原始值?

Year = groupItem.Key.Year == "" ? "Not Available" : string.Format("{0}", (int?)groupItem.Key.Year), 
Month = groupItem.Key.Month == "" ? "Not Available" : string.Format("{0:00}", (int?)groupItem.Key.Month), 
+0

我没有考虑这样做,但当我尝试我得到的错误“The'=='运算符不能应用于int的oeprands和字符串“。 – 2012-07-30 20:49:51

+0

所以它意味着你的'Year'和'Month'不像你写的那样是空字符串,而是'int's。作为int,它们不能为空,所以这就是为什么你的测试总是失败。所有这些意味着你的数据*源*在某种程度上是错误的。 – 2012-07-30 20:52:33