This project is read-only.

firstOrDefault seems not to work

Apr 2, 2011 at 9:56 PM

Hi,

firstOrdefault method seems not to work.

I've tried the following in '01-simple.php' example and it returns nothing (not NULL, just nothing)

$result = from('$n')->in($names)->firstOrDefault('$n => $n == "Joe"');

May be I do something wrong?

Thank you.

Apr 5, 2011 at 7:12 AM

Currently, the "default" for a string is null. Should this be ""?

Apr 5, 2011 at 6:52 PM

No-no-no! It should remain null. 

Actually I was wrong in first message - functions DO return something, but something strange. Look at following code (and remarks):

<?php

/** PHPLinq_LinqToObjects */
require_once 'PHPLinq/LinqToObjects.php';

class TestClass
{
    public $var1, $var2;
    public function __construct($v1, $v2)
    {
        $this->var1 = $v1;
        $this->var2 = $v2;
    }
}

$members = array();
//add two members to array
$members[] = new TestClass("USD", "CHF");
$members[] = new TestClass("GBP", "JPY");
//print array - it's shown as expected, with "USD-CHF" and "GBP-JPY" pairs
var_dump($members);
echo("<br />");
//try any
$result = from('$m')->in($members)->any('$m->var1 = "GBP"');
//works ok - "true" is shown
var_dump($result);
echo("<br />");
//try firstOrdefault
$result = from('$m')->in($members)->firstOrDefault('$m->var1 = "GBP"');
//I expect to see the object, but string(3) "GBP" is shown instead
var_dump($result);
echo("<br />");
//try where
$result = from('$m')->in($members)->where('$m->var1 == "GBP"')->select('$m');
//I expect to see only one object, but two objects with wrong currencies are shown - see results
var_dump($result);
echo("<br />");

//everything works with simple strings array BUT:
//it works when I use '=' in expression, if I use '==' results are wrong
$arr = array('one', 'two', 'three', 'four');
$result = from('$m')->in($arr)->any('$m = "two"');
var_dump($result);
echo("<br />");
$result = from('$m')->in($arr)->firstOrDefault('$m = "two"');
var_dump($result);
echo("<br />");
?>

And here are results:

array(2) { [0]=> object(TestClass)#1 (2) { ["var1"]=> string(3) "USD" ["var2"]=> string(3) "CHF" } [1]=> object(TestClass)#2 (2) { ["var1"]=> string(3) "GBP" ["var2"]=> string(3) "JPY" } }
bool(true)
string(3) "GBP"
array(2) { [0]=> object(TestClass)#1 (2) { ["var1"]=> string(3) "GBP" ["var2"]=> string(3) "CHF" } [1]=> object(TestClass)#2 (2) { ["var1"]=> string(3) "GBP" ["var2"]=> string(3) "JPY" } }
bool(true)
string(3) "two"

Something wrong with objects and with "=="