Type casting from IEnumerable to ObservableCollection in C#
While an ObservableCollection<T>
is IEnumerable<T>
the opposite does not hold. Try a constructor:
new ObservableCollection<SometypeType>(
testObservableList.Where(x => x.IsActiveForBid))
UWP Convert IEnumerable to ObservableCollection (x:Bind)
It's not updated because of how the ObservableCollection
works - it notifies only about changes inside the collection but when you are assigning the MessageList
in your SetMessages
method, you're creating new instance of ObservableCollection
and the ListView.Source
is pointing to the original bound instance of ObservableCollection
.
Also, I see that MessageList
is not a property, but field. Fields doesn't work with bindings.
You have four options how to achieve updating of the ListView
:
1) You could synchronize the existing MessageList
with new data:
private async Task SetMessages()
{
IEnumerable newData = await channel.GetMessagesAsync(20).Flatten();
// Assuming MessageList is not null here you will sync newData with MessageList
}
2) If you are not using the MessageList
collection anywhere else, you can set the ItemsSource
property of ListView
directly from code:
private async Task SetMessages()
{
YourListView.ItemsSource = await channel.GetMessagesAsync(20).Flatten();
}
3) Since you are using the x:Bind
expression, you can call Bindings.Update();
method everytime you want to refresh any binding on the page:
private async Task SetMessages()
{
MessageList = new ObservableCollection<IMessage>(await channel.GetMessagesAsync(20).Flatten());
Bindings.Update();
}
4) You could implement INotifyPropertyChanged
on the page or create DependencyProperty
for the MessageList
and then bind it with Mode
set to OneWay
:
<ListView ItemsSource="{x:Bind MessageList, Mode=OneWay}">
Personally I'd not recommend the fourth option. The best option would be to sync the data since ListView
automatically animates adding and removing the ListViewItems.
EDIT:
I think the problem is in these two lines:
messageList.Add(arg);
messageList.Remove(messageList[NumOfMessages - 1]);
since new items are added at the end of the collection, so you are removing the item you added last time. For deleting the oldest item, you should use messageList.RemoveAt(0);
to remove the item at the first position.
Cast IEnumerable into ObservableCollection
If the underlying object is not ObservableCollection
, nor any of its descendants, then simply can't do that.
"Casting" an object does one of two things:
- A cast, reinterpret the reference to a different type, this only works if the underlying type is that different type, or implement the interface if you're casting to interface.
- A conversion, like
int a = (int)dbl;
In your case neither will work as there is no such conversion available, and reinterpretation only works if the underlying type is a ObservableCollection
, so you're left with what you don't want to do:
You need to create a new ObservableCollection
Cannot convert type IEnumerable to ObservableCollection...are you missing a cast?
ObservableCollection<T>
has an overloaded constructor that accepts an IEnumerable<T>
as a parameter. Assuming that your Linq statement returns a collection of MasterPartsList
items:
public ObservableCollection<MasterPartsList> ParentAssemblyBOM
{
get
{
var enumerable = this._parentAssemblyBOM
.Where(parent => parent.isAssy == true);
return new ObservableCollection<MasterPartsList>(enumerable);
}
}
Convert ListT to ObservableCollectionT in WP7
Apparently, your project is targeting Windows Phone 7.0. Unfortunately the constructors that accept IEnumerable<T>
or List<T>
are not available in WP 7.0, only the parameterless constructor. The other constructors are available in Silverlight 4 and above and WP 7.1 and above, just not in WP 7.0.
I guess your only option is to take your list and add the items into a new instance of an ObservableCollection
individually as there are no readily available methods to add them in bulk. Though that's not to stop you from putting this into an extension or static method yourself.
var list = new List<SomeType> { /* ... */ };
var oc = new ObservableCollection<SomeType>();
foreach (var item in list)
oc.Add(item);
But don't do this if you don't have to, if you're targeting framework that provides the overloads, then use them.
Convert a ListT into an ObservableCollectionT
ObservableCollection < T > has a constructor overload
which takes IEnumerable < T >
Example for a List of int
:
ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);
One more example for a List of ObjectA
:
ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);
Cast LINQ result to ObservableCollection
Just use:
ObservableCollection<Foo> x = new ObservableCollection<Foo>(enumerable);
That will do the required copying. There's no way of observing changes to the live query - although the idea of an ObservableQuery<T>
is an interesting (though challenging) one.
If you want an extension method to do this, it's simple:
public static ObservableCollection<T> ToObservableCollection<T>
(this IEnumerable<T> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return new ObservableCollection<T>(source);
}
Related Topics
How to Disable a System Device Programmatically
How to Get the Last Five Characters of a String Using Substring() in C#
Server Execution Failed (Exception from Hresult: 0X80080005 (Co_E_Server_Exec_Failure))
How to Return an Anonymous Type from a Method
What Is a Predicate Delegate and Where Should It Be Used
Differences Between Iqueryable, List, Ienumerator
Serializing an Object as Utf-8 Xml in .Net
How to Use Showdialog Without Blocking All Forms
C# How to Find If an Event Is Hooked Up
How to Programmatic Disable C# Console Application's Quick Edit Mode
Alternatives to Thread.Sleep()
Replacing a Char at a Given Index in String
Loading a Full Hierarchy from a Self Referencing Table with Entityframework.Core
How to Convert Bitarray to Single Int
Getting Individual Windows Application Current Volume Output Level as Visualized in Audio Mixer
Help with a Oledb Connection String for Excel Files