Changing IQueryable, How does Link Type not work?

In C # it is often used to modify objects in private methods, since they are usually reference types instead of value types, for example:

public void Main()
{
    var person = new Person();

    SetPersonsName(person);

    System.Writeln(person.Firstname + " " + person.Lastname);
}

private void SetPersonsName(Person person)
{
    person.Firstname = "Jimi";
    person.Lastname = "Hendrix";
}

Name and Surname are applied to the object and will be correctly printed, because we pass the object by reference (a pointer to its location in memory), and do not create a copy of the object, as we would for value types.

So, what if we have IQueryable and which should use the same approach to add Where clauses to the collection of objects, for example below?

public void Main()
{
    // Returns Jimi Hendrix and Justin Bieber
    var people = _workspace.GetDataSource<Person>();

    FilterByRockGods(people);

    foreach(var person in people)
    {
        // Will still print "Jimi Hendrix" and "Justin Bieber"
        // Should only print "Jimi Hendrix" (obviously)
        System.Writeln(person.Firstname + " " + person.Lastname);
    }
}

private void FilterByRockGods(IQueryable<Person> people)
{
    people = people.Where(x => x.IsRockGod);
}

This will not work; the Where clause used in the private method does not apply to the collection

Instead, you should do the following:

public void Main()
{
    // Returns Jimi Hendrix and Justin Bieber
    var people = _workspace.GetDataSource<Person>();

    people = FilterByRockGods(people);

    foreach(var person in people)
    {
        // Prints "Jimi Hendrix"
        System.Writeln(person.Firstname + " " + person.Lastname);
    }
}

private IQueryable<Person> FilterByRockGods(IQueryable<Person> people)
{
    people = people.Where(x => x.IsRockGod);

    return people;
}

Why is this?

+4
1

, , person.Firstname = ..., FirstName, .

Where, , IEnumerable, IEnumerable.

+5

All Articles