Expose LinQ generated collection

Eduardo Lorenzo

Regular
Joined
Jun 27, 2006
Messages
87
Hi guys.

Am playing around with LinQ here, using VS2008Express. And I have this:

Visual Basic:
private void QueryData()
        {
            var peopleOlderThan = from p in people
                                  where p.Birthday < DateTime.Parse(textBox1.Text)
                                  orderby p.Name ascending
                                  select p;

            dataGridView1.DataSource = new BindingSource(peopleOlderThan, null);
         }

don't mind the part with the combobox. This statement basically gets data from here:

Visual Basic:
 people = new List<Person>();
            people.Add(new Person("Timmy", DateTime.Parse("1/2/1990")));
            people.Add(new Person("Gerald", DateTime.Parse("2/9/1979")));
            people.Add(new Person("Brian", DateTime.Parse("12/29/1973")));

This works ok, but I was just wondering if there is a way to expose peopleOlderThan outside of the method? Right now, what I do is put it in a function and return it as IEnumerable.

Visual Basic:
private IEnumerable getList()
        { 
        var peopleOlderThan = from p in people
                                  where p.Birthday < DateTime.Parse(textBox1.Text)
                                  orderby p.Name ascending
                                  select p;
        return peopleOlderThan;
        }

all inputs are welcome.
 
You could try something like
C#:
IEnumerable<Person> peopleOlderThan;

private void QueryData()
{
peopleOlderThan = from p in people
    where p.Birthday < DateTime.Parse(textBox1.Text)
    orderby p.Name ascending
    select p;

dataGridView1.DataSource = new BindingSource(peopleOlderThan, null);
}

You should then be able to access peopleOlderThan in other methods etc. by using a generic IEnumerable at least you also get proper intellisense throughout your code as well.

If you are messing with multiple threads then the above code is probably a disaster waiting to happen unless you implement some proper synchronisation .
 
I did this:

Visual Basic:
public ReadOnlyCollection<Person> GetPersons 
{ 
get { return peopleOlderThan.AsReadOnly(); } 
}

and am testing right now. Yes PD, the method you posted does supply intellisense but I heeded you warning and didn't use it. I am creating a "faux" data layer so I won't be sure how it will be consumed by other devs so I really want to be on the safe side of this. Thanks soooo much!
 
Back
Top