0

I'm working on converting my project from MySQL to MongoDB. I'm converting a few statements to MongoDB by using LinQ.

Here is my Original Statement:

SELECT COUNT(machinelograwdata.Parameter1) AS 'HideSheetCounter', 
    machinelograwdata.Parameter42 AS 'Orders', 
    machinelograwdata.MachineID 
FROM machinelograwdata 
WHERE EventID = '14' 
    AND CONVERT( Parameter35 , DECIMAL) <> 0 
    AND machinelograwdata.StartTime <= ' strSearchingEndDate + ' 
    AND machinelograwdata.StartTime >= ' strSearchingStartDate + ' 
GROUP BY Parameter42 , machinelograwdata.MachineID

and I try the following LinQ syntax and I got error:

var Temp3 = from c in MachineCollection.AsQueryable()
        where c.StartTime >= DateTime.Parse(strSearchingStartDate)
              && c.StartTime <= DateTime.Parse(strSearchingEndDate)
              && c.EventID == "14"
              && c.Parameter35 != "0"
        group c by new { c.Parameter42, c.MachineID } into grps
        select new
        {
            MachineID = grps.Key.MachineID,
            Orders = grps.Key.Parameter42,
            HideSheetCounter = grps.Count(x => x.Parameter1)
        };

Visual Studio raises issues at select and x.Parameter1 For x.Parameter1, the error is Cannot implicitly convert type 'string' to 'bool'
but my POCO is

[BsonElement("Parameter1")]
public string Parameter1
{
    get;
    set;
}

What is my code wrong? Could you give me some hints? Thank you

4
  • Count() expects a predicate (an expression returning true for each element you wish to count). Remove that part: x => x.Parameter1 Commented Oct 7, 2017 at 8:08
  • Thank you, @FedericoDipuma. But if I remove "x => x.Parameter1" , the result is not same with Original Statement Result. Commented Oct 7, 2017 at 8:11
  • 1
    If you want the same behavior (ignore the null values for Parameter1) then add that predicate inside Count(): Count(x => x.Parameter1 != null) Commented Oct 7, 2017 at 8:13
  • ah, now i understand more about LinQ based on your Count() : Count(x => x.Parameter1 != null) Thank you so much, @FedericoDipuma Commented Oct 7, 2017 at 8:21

1 Answer 1

2

The Count() method needs a predicate which returns a boolean for each element you want to count satisfing that condition.

To mimic the same behavior of COUNT(columnName) you need to provide the method a predicate which excludes null values for your field:

grps.Count(x => x.Parameter1 != null)
Sign up to request clarification or add additional context in comments.

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.