【问题标题】:Cast<> for hierarchical data structureCast<> 用于分层数据结构
【发布时间】:2015-07-20 15:10:07
【问题描述】:

这是一个例子

class A
{
    public string Text = "";
    public IEnumerable<A> Children = new List<A>();
}
class B
{
    public string Text;
    public IEnumerable<B> Children = new List<B>();
}

static void Main(string[] args)
{
    // test
    var a = new A[]
    {
        new A() { Text = "1", Children = new A[]
        {
            new A() { Text = "11"},
            new A() {Text = "12"},
        }},
        new A() { Text = "2", Children = new A[]
        {
            new A() {Text = "21", Children = new A[]
            {
                new A() {Text = "211"},
                new A() {Text = "212"},
            }},
            new A() {Text = "22"},
        }},
    };

    B[] b = a ...;  // convert a to b type

}

我最初的问题是模型中的分层数据A,它必须显示在视图中,因此我必须使用INotifyPropertyChanged等在ViewModel中创建B类型。从A转换为@987654327用于分层数据的 @ 似乎比简单的 linq Cast&lt;&gt; 更复杂。

如果有人要尝试编码,那么here 是一个很好的讨人喜欢的功能,可以这样使用:

foreach (var item in b.Flatten(o => o.Children).OrderBy(o => o.Text))
    Console.WriteLine(item.Text);

【问题讨论】:

  • 您要自行回答,然后更新问题以匹配答案吗?不太确定您正在寻找什么样的帮助。假设您已经有了递归代码,最好用您所拥有的以及为什么它不适合您来更新问题。
  • @AlexeiLevenkov,你说递归?由于某些原因,我无法做到,我最近的想法是展平a,然后是Cast&lt;&gt;,然后展平......我坚持展平。也许我过于复杂了?如果这对您来说听起来很简单,您能发表一个答案吗?
  • Sinatr,StripligWarior 的回答(由于某种奇怪的原因被否决)工作得非常好,可能是您需要编写的最短代码。

标签: c# linq converter hierarchy


【解决方案1】:

使用可以将A 转换为B 的递归函数。

B BFromA(A a) {
    return new B { Text = a.Text, Children = a.Children.Select(BFromA).ToList() };
}

用法:

B[] b = a.Select(BFromA).ToArray();  // convert a to b type

【讨论】:

  • @Sinatr 代码运行良好。将方法名称(“方法组”)作为委托传递绝对没有什么特别之处。
  • @Sinatr: .Select()System.Linq 命名空间中的扩展方法。您需要将 using System.Linq; 添加到 C# 文件的顶部,就像 Alexei 在他的示例中所做的那样。 LINQ 扩展方法被大量使用,以至于我们倾向于认为您将包含此命名空间是理所当然的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2010-12-22
  • 2015-03-12
  • 2023-03-31
相关资源
最近更新 更多