You cannot implement any of the solutions listed here until your types are the same! For example, if your list or ICollection or IEnumerable is of type string , but your ObservableCollection must be of type Nodes or Computers or something else, you must first get a List of this type! I spent so much time on these other fictitious, simplified "solutions" that are NOT solutions because they do not explain this or do not take this factor into account.
Say this is your ObservableCollection :
public class Computer { public string Name { get; set; } }
Pretty standard, right? You are likely to replace Computer with any number of objects in any number of projects.
If you then get a list of computer names in a List<string> called lstComputers , you CANNOT just convert this using:
var oc = new ObservableCollection<Computer>(lstComputers);
He will say that your types are incompatible and cannot be converted from one to another, because you are trying to drag the List<string> into the ObservableCollection<Computer> . Square snap in a round hole.
Instead, in your function to get the names of computers, you should add all of them "special":
public static List<Computer> NetworkComputers() { List<Computer> lstComputers = new List<Computer>(); DirectoryEntry root = new DirectoryEntry("WinNT:"); foreach (DirectoryEntry computers in root.Children) { foreach (DirectoryEntry computer in computers.Children) { if (computer.Name != "Schema" && computer.SchemaClassName == "Computer") { lstComputers.Add(new Computer() { Name = computer.Name }); } } } }
Just because we used this line lstComputers.Add(new Computer() { Name = computer.Name }); and return List<Computer> , not List<string> , can we now put it in our ObservableCollection<Computer> .
If you missed a boat and cannot do it from the very beginning, this thread talks about other ways you could do: convert a list of objects from one type to another using the lambda expression
So, as soon as you get it in the List<Computer> , only then you can do:
List<Computer> lstComputers = NetworkComputers(); var oc = new ObservableCollection<Computer>(lstComputers);