0

I am having some trouble in converting the following code to use LINQ.

int occurs = 0;
foreach (string j in items)
{
if (!string.IsNullOrEmpty(j))
            {
                WorkflowModule tempWM = new WorkflowModule(j);
                if (tempWM.StateID == item.StateID)
                {
                    occurs++;
                }
            }
        }
        return occurs;

So far, I have:-

var lstItems = (from lstItem in items
                        where !string.IsNullOrEmpty(lstItem)
                        let objWorkflowModule = new WorkflowModule(lstItem)
                        select new
                        {
                            tempWM = objWorkflowModule.StateID
                        }).Where(item.StateID == tempWM));

        return lstItems.Count();

but intellisense is not liking the line '.Where(item.StateID == tempWM))'

Can anyone help me achieve this?

Thanks.

3 Answers 3

6

When you use the method syntax, you need to use a lambda on the Where operator:

...
}).Where(x => x.tempWM == item.StateID));

In other words, you need to "declare" the variable x which holds the result of the previous part of the query.

Sign up to request clarification or add additional context in comments.

1 Comment

I think they actually want Where(t => t.tempWM == item.StateID) because item seems to be a variable defined outside the original code.
0

It doesn't look like item is initialized anywhere in your statement.

Comments

0

Here's how I'd do this

var lstItems = from lstItem in items
               where !string.IsNullOrEmpty(lstItem)
               let objWorkflowModule = new WorkflowModule(lstItem)
               select objWorkflowModule.StateID;

return lstItems.Count(t=> t == item.StateID);

I'm assuming item is a variable defined outside of the original code you submitted. Basically you don't need to create the anonymous class in the query and you can put the predicate in you're Where into Count instead. But as others have said the main issue is that you need to express your predicate as a lambda.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.