C# 将 List<Object> 转换为 ObservableCollection<Object> 的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9069445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:47:08  来源:igfitidea点击:

The best way to convert List<Object> to ObservableCollection<Object>

c#.netwpf

提问by Terminador

I have got List<Object>where the Objecthas a lot of childs List<Object>around 4-6 levels.

我已经List<Object>知道对象List<Object>在 4-6 级左右有很多孩子的地方。

Now I have to bind it to WPF TreeView... :(

现在我必须将它绑定到 WPF TreeView ... :(

Which the best wayto convert it into ObservableCollection<Object>is?

将其转换为哪种最佳方法ObservableCollection<Object>是?

采纳答案by Mharlin

One part of the answer is to use Reactive Extensions (Rx). You can get it from NuGet and it's developed by Microsoft. With the help of it you can simply say: myListCollection.ToObservable();

答案的一部分是使用 Reactive Extensions (Rx)。您可以从 NuGet 获取它,它是由 Microsoft 开发的。借助它,您可以简单地说:myListCollection.ToObservable();

If your child collections always are in a node with the same name you could use a while(item.Collection != null || item.Collection.Count == 0)and put the ToObservable()within the loop

如果您的子集合始终位于同名的节点中,则可以使用 awhile(item.Collection != null || item.Collection.Count == 0)并将其放入ToObservable()循环中

回答by James Michael Hare

Assuming you mean ObservableCollection<T>, if you wanted the Listdirectly to the ObservableCollectionas-is, just use the constructor:

假设你的意思是ObservableCollection<T>,如果你想List直接按ObservableCollection原样使用,只需使用构造函数:

var oc = new ObservableCollection<Object>(yourListOfObject);

Now, if you're wanting to unwind each of those, you would need to do some work to collapse them into a single ObservableCollection<T>.

现在,如果您想展开其中的每一个,您需要做一些工作将它们折叠成一个ObservableCollection<T>.

回答by Chris Trombley

I assume you're talking about ObservableCollection. To answer simply, you can use the ctor:

我假设你在谈论 ObservableCollection。简单回答,你可以使用ctor:

List<Object> myList = GetList();
new ObservableCollection<Object>(myList);

However, I think there is some work left to be done in terms of organizing your information hierarchically.

但是,我认为在分层组织信息方面还有一些工作要做。

回答by Miserable Variable

Do you mean ObservableCollection? If you want the child level Liststo be observable also then you will need to traverse the tree and change items as necessary or add each item separately to begin with.

你的意思是ObservableCollection吗?如果您希望子级别Lists也可观察,那么您将需要遍历树并根据需要更改项目或单独添加每个项目开始。

回答by Douglas

Assuming you have a node class defined like so:

假设你有一个像这样定义的节点类:

public class Node
{
    public ICollection<Node> Children { get; set; }
}

You can use recursion to convert List<Node>collections, at any level of depth:

您可以使用递归转换List<Node>任何深度级别的集合:

public static ObservableCollection<Node> ToObservableRecursive(ICollection<Node> nodes)
{
    foreach (Node node in nodes)
        if (node.Children != null)
            node.Children = ToObservableRecursive(node.Children);

    return new ObservableCollection<Node>(nodes);
}

回答by vapcguy

You cannot do any of the solutions listed here until your types are the same! If your list or ICollection or IEnumerable is of type string, for example, but your ObservableCollectionneeds to be of type Nodesor Computersor something else, you have to get the List into that type, first! I wasted so much time on these other bogus, simplified "solutions" that are NOT solutions because they do not explain this or take this factor into account.

在您的类型相同之前,您无法执行此处列出的任何解决方案!如果列表或ICollection的或IEnumerable的类型是string,例如,但你ObservableCollection需要为类型NodesComputers或别的东西,你必须让列表进入该类型,第一个吧!我在这些其他虚假的、简化的“解决方案”上浪费了很多时间,这些“解决方案”不是解决方案,因为它们没有解释这一点或考虑到这个因素。

Say this is your ObservableCollection:

说这是你的ObservableCollection

public class Computer
{
    public string Name { get; set; }
}

Pretty standard, right? You'd probably end up replacing Computerwith any number of things in any number of projects.

很标准吧?您可能最终会Computer在任意数量的项目中替换任意数量的东西。

If you then get a list of computer names in a List<string>called lstComputers, you CANNOT just convert that using:

如果你在一个List<string>被调用的文件中得到一个计算机名称列表lstComputers,你不能只使用以下方法转换它:

var oc = new ObservableCollection<Computer>(lstComputers);

It will say your types are mismatched and cannot be converted from one to the other because you are trying to shove a List<string>into an ObservableCollection<Computer>. Square peg in a round hole.

它会说您的类型不匹配并且无法从一种转换为另一种,因为您试图将 a 推List<string>入 an ObservableCollection<Computer>。圆孔中的方钉。

Instead, in your function for getting the computer names, you have to add them all "special-like":

相反,在获取计算机名称的函数中,您必须将它们全部添加为“类似”:

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 });
            }
        }
    } 
}

Only because we used that line lstComputers.Add(new Computer() { Name = computer.Name });and are returning the List<Computer>and not List<string>can we now put it into our ObservableCollection<Computer>.

只是因为我们使用了该行lstComputers.Add(new Computer() { Name = computer.Name });并且返回了List<Computer>and notList<string>我们现在可以将它放入我们的ObservableCollection<Computer>.

If you missed the boat and can't do it like this from the start, this thread talks about other ways you might be able to do your conversion: convert a list of objects from one type to another using lambda expression

如果您错过了船并且从一开始就不能这样做,这个线程讨论了您可能能够进行转换的其他方法: 使用 lambda 表达式将对象列表从一种类型转换为另一种类型

So once you have it in a List<Computer>, only then you can do:

所以一旦你在 a 中拥有它List<Computer>,只有这样你才能做到:

List<Computer> lstComputers = NetworkComputers();
var oc = new ObservableCollection<Computer>(lstComputers);