【问题标题】:variable content set by webservicewebservice设置的可变内容
【发布时间】:2012-04-16 17:40:34
【问题描述】:

我有一个休息服务,它有一个组列表,每个组都有一个 GroupName,在我的客户端,我试图将这些 GroupName 添加到变量 groupbox 的列表中(groupbox 的数量取决于我有多少 GroupName rest 组服务)有人可以帮忙写代码吗?:

        string uriGroups = "http://localhost:8000/Service/Group";
        XDocument xDoc = XDocument.Load(uriGroups);
        var groups = xDoc.Descendants("Group")
        .Select(n => new
        {
            GroupBox groupbox = new GroupBox();
            groupbox.Header = String.Format("Group #{0}", n.Element("GroupName");
            groupbox.Width = 100;
            groupbox.Height = 100;
            groupbox.Margin = new Thickness(2);

            StackPanel stackPanel = new StackPanel();
            stackPanel.Children.Add(groupbox);
            stackPanel.Margin = new Thickness(10);

            MainArea.Children.Add(stackPanel);
        }

这是不正确的,我只是坚持如何去做。

编辑:

    public Reports()
    {
        InitializeComponent();

        string uriGroups = "http://localhost:8000/Service/Group";
        XDocument xDoc = XDocument.Load(uriGroups);
        foreach(var node in xDoc.Descendants("Group"))
        {

            GroupBox groupbox = new GroupBox();
            groupbox.Header = String.Format("Group #{0}", node.Element("Name")); 
            groupbox.Width = 100;
            groupbox.Height = 100;
            groupbox.Margin = new Thickness(2);

            StackPanel stackPanel = new StackPanel();
            stackPanel.Children.Add(groupbox);
            stackPanel.Margin = new Thickness(10);

            MainArea.Children.Add(stackPanel);
        }

    }
    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
    {
        foreach (var item in enumerable)
            action(item);

        return enumerable;
    }

【问题讨论】:

    标签: c# wpf wcf rest


    【解决方案1】:

    1) 您不应该使用 LINQ Select 扩展来遍历集合并做某事;它只能用于将元素转换为新形式。如果你想做这样的事情,要么只使用foreach 语句,要么创建一个新的 LINQ 扩展来处理这样的枚举:

      public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
      {
           foreach(var item in enumerable)
               action(item);
    
           return enumerable;
      }
    

    2) 上面的代码不应该编译,因为它在语法上被破坏了。您尝试做的是创建一个新的匿名类型(new { })。由于您没有在此对象上创建属性,而是尝试执行随机代码行(这是不允许的),因此这是无效的。当创建一个匿名类型时,你会做这样的事情:

     Enumerable.Range(0, 10).Select(x => new { Number = x });
     // Creates a series of 10 objects with a Number property
    

    3) 听起来您只需将代码重构为适当的代码即可完成此任务。除了非编译部分之外,我没有看到您遇到的特定问题。

    【讨论】:

    • 嘿,我只是卡在代码上,我不知道如何实现你所说的:S
    • 例如,不要使用Select,只需创建一个foreach(var node in xDoc.Descendents("Group")),然后在您的代码中使用item而不是n
    • 但 system.Linq 不包含后代的定义?
    • 此外,您将迭代器变量称为node,而不是item。在你的代码中使用node,因为那是你使用的。
    • 正确,因为您使用的是foreach 语句,所以您实际上并不需要该方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2012-01-04
    相关资源
    最近更新 更多