0

I have the following Mongodb Script but would like to write them in C#, can somebody help me translate them to C# as simple as possible. I am using mongodb C# driver.

Find the max value of a field in a collection and return it to a variable

db.tblProduct.find().sort({"ThrowNo":1/-1}).limit(-1)

Find the min value :

db.tblProduct.find().sort({"ThrowNo":1/1}).limit(-1)

How would I handle converting different datatypes for example if ThrowNo would be a datetime.

Thanks you for assisting me!

Nyra
  • 859
  • 1
  • 7
  • 27
Hao
  • 1
  • You may want to go down some of the [LINQ](http://stackoverflow.com/questions/15265588/how-to-find-item-with-max-value-using-linq) post rabbit holes- I think that will be your best option. – Nyra Nov 18 '14 at 18:54
  • Use `OrderBy` (or `OrderByDescending`) and `First` – D Stanley Nov 18 '14 at 19:20

3 Answers3

0

Not sure exactly how to translate the scripts but

db.tblProduct.OrderBy(p => p.ThrowNo).First();

and

db.tblProduct.OrderByDescending(p => p.ThrowNo).First();

will return the entities with the lowest and highest ThrowNo values.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

Below method sorts a given collection, after which you would need to apply the first function

public ICollection<T> getSortedData(ICollection<T> collection, string property, string direction)
{
    switch (direction.Trim())
    {
      case "asc":
        collection = ((from n in collection
                       orderby
                       n.GetType().GetProperty(property).GetValue(n, null)
                       select n).ToList<T>()) as ICollection<T>;
      break;
      case "desc":
        collection = ((from n in collection
                       orderby
                       n.GetType().GetProperty(property).GetValue(n, null)
                       descending
                       select n).ToList<T>()) as ICollection<T>;
      break;
   }
  return collection;
}

var firstProduct = getSortedData(products,"ThrowNo","desc").first<Product>();
Mothupally
  • 750
  • 2
  • 8
  • 16
0

collection.OrderBy(item => item.ThrowNo) uses Linq and it requires load all docs then set order on them in memory

The exact code matches with c# is something like:

collection.FindAll().SetSortOrder(SortBy.Ascending("ThrowNo")).SetLimit(-1);
Disposer
  • 6,201
  • 4
  • 31
  • 38