I have a rest service which has a list of Groups each group has a GroupName and on my client side I am trying to add those GroupName’s to a list of variable groupbox’s (number of groupboxes depends on how many GroupNames there is in my rest Group service) can anyone help with the code?:
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);
}
This isnt correct I am just stuck on how to do it.
EDIT:
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;
}
1) You shouldn’t be using the LINQ
Selectextension to iterate over the collection and do something; it should only be used to transform the element into a new form. If you want to do something like this, either just use aforeachstatement, or make a new LINQ extension to work on the enumerable like so:2) The above code shouldn’t compile because it’s syntactically broken. What you’re attempting to do is make a new anonymous type (the
new { }). Since you’re not making properties on this object, and instead trying to execute random lines of code (which is not allowed), this is not valid. When making an anonymous type, you would do something like this:3) It sounds like you just need to refactor your code to the appropriate code to get this done. I’m not seeing the particular problem you are having, other than the non compiling part.