Steve Staple
Steve Staple

Reputation: 3279

Interpreting difficult linq statement

What does this statement do? It is the last line that has me baffled.

    foreach (View_ManSchedAllocatedTask task in
              manualScheduleData.GetAllocatedTasks(DateTime.Now)
                                .Where(x => !x.Status.Equals("999B"))
                                .Where(x => x.LetterSent == false)
                                .Where(x => x.Stage.Equals(missed ? "51" : "06")))

Upvotes: 1

Views: 115

Answers (6)

Sria Pathre
Sria Pathre

Reputation: 182

The given statement iterates loop for all the task those are allocated at current time stamp, whose status is not '999B', its LetterSent is false and stage is 51 or 06 (according to value of missed as explained above.)

Upvotes: 1

Dave Bish
Dave Bish

Reputation: 19646

It's using the Conditional Operator which is like a short-hand 'if' statement.

So, It's the same as this:

var stageToCompare = "";

if(missed == true)
    stageToCompare = "51";
else
    stageToCompare = "06";


foreach (View_ManSchedAllocatedTask task in manualScheduleData.GetAllocatedTasks(DateTime.Now)
    .Where(x => !x.Status.Equals("999B"))
    .Where(x => x.LetterSent == false)
    .Where(x => x.Stage.Equals(stageToCompare)));

Upvotes: 1

Chris Mantle
Chris Mantle

Reputation: 6683

It's probably easier to visualize with the ternary operator (?:) expanded into an if statement:

.Where(x => x.Stage.Equals(missed ? "51" : "06")))

is equivalent to:

.Where(
    x =>
    {
        if (missed)
        {
            return x.Stage.Equals("51");
        }
        else
        {
            return x.Stage.Equals("06");
        }
    });

Upvotes: 1

BG100
BG100

Reputation: 4531

Its only including data where Stage is either "51" or "06" depending on whether the missed variable is true or false.

Upvotes: 0

xuma202
xuma202

Reputation: 1084

It is probably the ternary statement that is somewhat confusing.

Where(x => x.Stage.Equals(missed ? "51" : "06"))

it basically means

if missed = true check for x.Stage.equals(51)

if missed = false check for x.Stage.equals(06)

Upvotes: 4

pid
pid

Reputation: 11597

I'll explain the line:

.Where(x => x.Stage.Equals(missed ? "51" : "06"))

The object x has a property Stage. If that Stage is equal to something it is inside the result set, otherwise x is outside the result set.

Now what is this something x.Stage has to be equal to?

If missed is true, it must be equal to "51", otherwise "06".

The value of missed is an invariant, so all elements in the result set will either have Stage "51" or "06" depending on missed.

The ternary operator is defined as follows:

result = expression ? truthy_value : falsy_value

::=

if (expression)
{
    result = truthy_value;
} else {
    result = falsy_value;
}

The ::= means is equal to.

Upvotes: 4

Related Questions