Question
· Feb 1, 2018

Achieving LINQ functionality in ObjectScript

WRF to below example my idea is to check whether red is present in the list mylist.  You can very well use LINQ on enumerable in C#

mylist.Where(x => (x.Property2 == "red")).ToList().Count;
set mylist=##class(%ListOfObjects).%New()

For i=1:1:2 {
  S object = ##class(User.NewClass).%New()
  S object.Property1=i
  S object.Property2="red"
  do mylist.Insert(object)  
}

It can be done with iterating over mylist

  for j=1:1:mylist.Count(){   
  Set item = mylist.GetAt(j)
   If (item.Property1 = "red") { // get the count }
   //set exist = item.Find("viv",1)
  }
Discussion (3)0
Log in or sign up to continue

Hello Vivek,

Microsoft LINQ adds query capability to .net.  You are asking whether similar things can be done with COS.

First, please confirm my understanding of your example.

Looking at our Sample.Person database, I see that property FavoriteColors is a list of strings. I can find or count all Persons with 'Red' as one of their FavoriteColors with SQL:
SELECT ID, FavoriteColors FROM Sample.Person WHERE FOR SOME %ELEMENT(FavoriteColors) (%VALUE='Red')
SELECT COUNT(*)           FROM Sample.Person WHERE FOR SOME %ELEMENT(FavoriteColors) (%VALUE='Red')

You can capture the count in COS code with:
 &sql(SELECT COUNT(*) INTO :myCount FROM Sample.Person WHERE FOR SOME %ELEMENT(FavoriteColors) (%VALUE='Red'))

So COS provides the desired functionality for objects stored in the database.

 
You seem to want to examine a list of objects in memory to count those that have Property2='Red'

If your objects are in memory but not on disk, then I don't believe that COS offers a similar facility to LINQ WHERE.  Hopefully, iterating is not a major inconvenience.