1

The first ternary statement in the following code is returning "null". myID is coming back as null. However, if the ternary statement worked properly, and a.someID is null, then myID should come back as -1. myID is a nullable int field. Do you know why I'm not getting back a -1? Thanks.

public List<myView> GetRecords()
{
    myEntities entities = new myEntities();

    var myValue = (from a in entities.myEntitiesA
                   join b in entities.myEntitiesB on a.myID equals b.myID into myEntitesC
                   from c in myEntitesC.DefaultIfEmpty()
                   select new myView
                   {
                       myID = a.someID == null ? -1 : a.someID,
                       myName = a.myName,
                       myAlternateID = c.myID == null ? -1 : c.myID,
                       myAlternateName = c.myName == null ? "" : c.myName,
                   }).Distinct().OrderBy(b => b.myName).ToList();

    return (myValue);
}

EDIT - I've gotten rid of the DefaultIfEmpty() for the sake of testing, but my results are the same.

4

4 に答える 4

0
  from c in myEntitesC.DefaultIfEmpty()
  select new myView
  {
    ...
    myAlternateID = c.myID == null ? -1 : c.myID, 

cがnullの場合はどうなりますか?

    myAlternateID = (c == null || c.myID == null) ? -1 : c.myID, 

Linqは、多くの異なる実装に対して共通の構文を使用してクエリを宣言する方法です。特定のクエリの実装は、LinqToObjectsではない場合があります(静的クラスで実装されている場合System.Linq.Enumerable)。最良の答えを得るには、クエリを実行しているシステムを指定するのが適切です。

于 2012-07-11T17:10:43.003 に答える
0

おそらく DefaultIfEmpty() ルーチンがトリガーされているため、三項演算子は実行されていませんが、新しい myView が作成されています。

于 2012-07-11T17:39:28.297 に答える
0

私はあなたがnullのcoallessing演算子を使いたいと思うかもしれません.??

// y = x, unless x is null, in which case y = -1.
        int y = x ?? -1;

から?? オペレーター文書

于 2012-07-11T17:00:13.763 に答える
0

他のすべての回答は有効に見えますが、どれも私にとってはうまくいきません。この GetRecords() メソッドを JsonResult コントローラー メソッドから呼び出していたため、JsonResult で追加のロジックを実行し、NULL をもう一度チェックすることになりました。もちろん、これは冗長なチェックなので理想的ではありませんが、機能します。

于 2012-07-30T02:12:39.057 に答える