Paul Michaels
Paul Michaels

Reputation: 16695

Creating a new ObservableCollection using a collection of classes

I have the following two classes:

 public class MyData
 {
     public MyData2 Data2 {get; set;}
 }

 public class MyData2
 {
     public string data {get; set;}
 }

I have an IList of MyData2, and I want to create a collection (ObservableCollection ideally, although I can easily convert) of MyData. I feel it should be possible t do this using a lambda statement, but I can't seem to come up with the syntax; something like:

IList<MyData2> myData2 = GetData();
ObservableCollection<MyData> myData = new ObservableCollection<MyData>(Data2 = myData2??);

Is there a way to do this using labda / LINQ, or do I need to use a foreach?

Upvotes: 1

Views: 4067

Answers (1)

Artem Mesha
Artem Mesha

Reputation: 157

Use Enumerable.Select Method:

var myData = myData2.Select(data2 => new MyData() { Data2 = data2 });
var collection = new ObservableCollection<MyData>(myData);

Upvotes: 3

Related Questions