2016-07-02 8 views
2

ich folgenden Code schreibt ein zählen bezieht sich Document auf:Schreiben wenn dann sonst in Linq to Entities-Abfrage

var currentStationId = GetCurrentStation(); 
var result = dbContext 
      .Documents 
      .Select(x=> 
        new MyDTO{ 
          ..., 
          ReferCounts = x.DocumentStationHistories 
              .Count(t => t.ToStationId == currentStationId)) 
          } 

Jetzt möchte ich Mechanismus ReferCounts der Berechnung ändern:

if(currentStationId == 1) ReferCounts = x.DocumentStationHistories 
             .Count(t => t.ToStationId == currentStationId && 
                t.FromStationId != t.ToStationId)) 
else 
    ReferCounts = x.DocumentStationHistories 
        .Count(t => t.ToStationId == currentStationId)) 

Wie kann Ich verwende diesen Code in meiner linq to entities-Abfrage?

+0

Was ist mit der Syntax [ternary if] (https://msdn.microsoft.com/en-us/library/ty67wk28.aspx)? – nlloyd

+0

Format ändern: (currentStationId == 1)? ReferCounts = x.DocumentStationHistories .Count (t => t.ToStationId == currentStationId && t.FromStationId = t.ToStationId!)) : ReferCounts = x.DocumentStationHistories .Count (t => t.ToStationId == aktuelleStationId)) – jdweng

Antwort

0

Hier ist ein Beispiel für die ternary if Syntax.

var result = dbContext 
     .Documents 
     .Select(x=> 
       new MyDTO{ 
         ..., 
         ReferCounts = (currentStationId == 1) ? 
          x.DocumentStationHistories.Count(t => t.ToStationId == currentStationId && t.FromStationId != t.ToStationId)) 
          : x.DocumentStationHistories.Count(t => t.ToStationId == currentStationId)) 
         }