8

I want the datacontext of my listview to be binded to an observable collection. Right now I have:

               // CurrentEmploye = some employee
               Entities.DatabaseModel m = new Entities.DatabaseModel();
               var q = from t in m.TimeSheet                            
                        join emp in m.Employees on t.idEmployee equals emp.id
                        where emp.id == CurrentEmploye.id
                        select new
                        {
                            firstName = emp.firstName,
                            lastName = emp.lastName,
                            position = emp.position,
                            clockInDate = t.clockInDate,
                            clockOutDate = t.clockOutDate,
                        };

                        listView1.DataContext = q;

that code populates the listview correctly. Now I will like to update the listview whenever I update a listview item.

I will like the variable q to be of type ObservableCollection without having to create a custom class that holds firstName, lastName, position, etc... How can I do that?

Tono Nam
  • 34,064
  • 78
  • 298
  • 470
  • 2
    I assume that you tried `listView1.DataContext = new ObservableCollection(q)` and it did not work, right?.. – Sergey Kalinichenko Apr 02 '12 at 22:20
  • 1
    new ObservableCollection<"need type">(q); requires a type and I don't know the type. maybe I'll get it with reflection. Thanks that was a helpful comment. – Tono Nam Apr 02 '12 at 22:24
  • 1
    Ah, you're right, I entirely forgot that what works with methods does not always work with constructors. Let's wait for Jon Skeet then :) – Sergey Kalinichenko Apr 02 '12 at 22:26
  • 2
    Cancel that wait! [He did it already](http://stackoverflow.com/questions/280172/create-generic-class-instance-based-on-anonymous-type)! – Sergey Kalinichenko Apr 02 '12 at 22:28
  • I guess I had a duplicate question then. Place that as an answer and I'll accept it. Thanks for the help. – Tono Nam Apr 02 '12 at 22:30

2 Answers2

15

You can cheat and create a method to do it for you since methods can infer the generic type automatically:

public ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> enumeration)
{
    return new ObservableCollection<T>(enumeration);
}

Oh, and if it helps you can create this as an extension method so it's easier to use... up to you.

myermian
  • 31,823
  • 24
  • 123
  • 215
  • Is there a way to do it without using generics? I mean, with inline code and without creating a real type. Something like ObservableCollection ? – v1n1akabozo Jun 12 '16 at 16:19
1

In addition to m-y answer, in order to use it as an extension you should put "this" before the method argument:

public ObservableCollection<T> ToObservableCollection<T>(this IEnumerable enumeration){ return new ObservableCollection<T>(enumeration) }