简体   繁体   中英

C# - convert anonymous type to observablecollection

I have a LINQ statement that returns an anonymous type. I need to get this type to be an ObservableCollection in my Silverlight application. However, the closest I can get it to a

List myObjects;

Can someone tell me how to do this?

ObservableCollection<MyTasks> visibleTasks = e.Result;
var filteredResults = from visibleTask in visibleTasks
                      select visibleTask;

filteredResults = filteredResults.Where(p => p.DueDate == DateTime.Today);
visibleTasks = filteredResults.ToList();  // This throws a compile time error

How can I go from a anonymous type to an observable collection?

Thank you

As Ekin suggests, you can write a generic method that turns any IEnumerable<T> into an ObservableCollection<T> . This has one significant advantage over creating a new instance of ObservableCollection using constructor - the C# compiler is able to infer the generic type parameter automatically when calling a method, so you don't need to write the type of the elements. This allows you to create a collection of anonymous types, which wouldn't be otherwise possible (eg when using a constructor).

One improvement over Ekin's version is to write the method as an extension method. Following the usual naming pattern (such as ToList or ToArray ), we can call it ToObservableCollection :

static ObservableCollection<T> ToObservableCollection<T> 
  (this IEnumerable<T> en) { 
    return new ObservableCollection<T>(en); 
} 

Now you can create an observable collection containing anonymous types returned from a LINQ query like this:

var oc = 
  (from t in visibleTasks   
   where t.IsSomething == true
   select new { Name = t.TaskName, Whatever = t.Foo }
  ).ToObservableCollection();

Something like this would do the job using type inference features:

private static ObservableCollection<T> CreateObservable<T>(IEnumerable<T> enumerable)
{
    return new ObservableCollection<T>(enumerable);
}

static void Main(string[] args)
{

    var oc = CreateObservable(args.Where(s => s.Length == 5));
}

你应该能够做到这一点:

visibleTasks = new ObservableCollection<MyTasks>(filteredResults);

Try:

var filteredResults = from visibleTask in visibleTasks
                      where(p => p.DueDate == DateTime.Today)
                      select visibleTask).ToList(); 

(filteredResults will contain your desired list)

Are you sure that your object is an ObservableCollection indeed? If yes, you can just cast: visibleTasks = (ObservableCollection)filteredResults;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM