2

I have a List that I want to cast to an ObservableCollection, this is my code

var list = Models.Lands.FromJson(responce.Result.ToString());
this.Lands = new ObservableCollection<Land>( list );

FromJson returns me a List<Models.Land>, and this.Lands is an ObservableCollection<Models.Land>.

new ObservableCollection<Models.Land>( list ) gives me the following error:

cannot convert from System.Collections.Generic.List<> to System.Collections.Generic.IEnumerable<>,

I thought that the constructor was overloaded for a List<> object.

taquion
  • 2,667
  • 2
  • 18
  • 29
  • 1
    What are they types given in your error? A `List` can be converted to an `IEnumerable` so presumably your generic objects are of different types but you seem to have stripped out this crucial information... – Chris Jun 22 '18 at 14:07
  • Possible duplicate of [How to convert IEnumerable to ObservableCollection?](https://stackoverflow.com/questions/3559821/how-to-convert-ienumerable-to-observablecollection) – d.moncada Jun 22 '18 at 14:19

3 Answers3

0

Try using the nongeneric var keyword.

List<Land> list =Models.Lands.FromJson(responce.Result.ToString());
var collection = new ObservableCollection<Land>(list);
0

I think you can do something like below to avoid your problem but still using a single line of code:

this.Lands = new ObservableCollection<Land>( list.ToArray<Land>());

but I'm not sure if that's an efficient way to do that.

Legion
  • 760
  • 6
  • 23
  • Why ToArray? The ObservableCollection constructor takes an IEnumerable so there is no need to copy all list elements to an array which is then copied to the ObservableCollection. – ckuri Jun 22 '18 at 16:40
  • I agree with you, but i encounter the same error times ago and without the "toArray" you got the error, with it the error disappear... The difference is that in Observable collection you're casting a Lands[] instead of List, but i agree that both should be converted into IEnumerable without any problem. – Legion Jun 28 '18 at 14:43
-1

Works in my browser: https://dotnetfiddle.net/VVB8YY

public static void Main()
{
    var list = new List<String>{"a", "b", "c"};
    var collection = new ObservableCollection<string>(list);

    foreach (var value in collection)
    {
        Console.WriteLine(value);
    }

    Console.WriteLine("Hello World");
}
Oliver
  • 43,366
  • 8
  • 94
  • 151