我有一个休息服务,其中有一个组列表,每个组都有一个GroupName,在我的客户端,我正在尝试将这些GroupName添加到变量groupbox的列表中(组框的数量取决于我的组中有多少个GroupNames)休息团体服务)任何人都可以帮助代码吗?:
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;
}
答案 0 :(得分:2)
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)听起来你只需要将代码重构为适当的代码即可完成。除了非编译部分之外,我没有看到您遇到的特殊问题。