0

私は次のLinqtoSQLを持っています:

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とMonthの両方に空の文字列があることです。この場合、空の文字列を「使用不可」に置き換えたいと思います。私はこのような三元ステートメントを実行しようとしました:

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

テスト。

何かアドバイス?

4

2 に答える 2

3

代わりに、LINQtoObjectsで最終操作を行うことを強くお勧めします。LINQ to SQLで必要なすべてのビットを投影してAsEnumerableから、LINQtoObjectsに戻るために使用します。

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 Objectsを使用している場合、複雑なシナリオで何が起こるかを考えるのははるかに簡単です。null処理などの違いについて心配する必要はありません。

于 2012-07-30T20:43:00.303 に答える
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),  
于 2012-07-30T20:42:23.217 に答える