简体   繁体   中英

How to convert the following foreach nested loop to LINQ?

Code:

foreach (var item in items.Children)
{
    RadTreeViewItem parent1 = new RadTreeViewItem();
    parent1.Header = NodeHeader(item.Path, item.Name, SelectedPath, ProjectData);
    parent1.Tag = item;
    foreach (var child in item.Children)
    {
        RadTreeViewItem children = new RadTreeViewItem();
        children.Header = NodeHeader(child.Path, child.Name, SelectedPath, ProjectData);
        children.Tag = child;
        parent1.Items.Add(children);
    }
    Parent.Items.Add(parent1);
}

items.Children and item.Children are ObservableCollection<>

parent1.Header and children.Header are HeaderedItemsControl.Header

parent1.Tag and children.Tag are FrameworkElement.Tag

How to convert the above foreach nested loop to LINQ ?

LINQ... Language INtegrated (and here's the key bit) Query .

What you are doing is not a query. Leave it with the foreach loops; it is fine, it is clear, it is obvious.

In particular, the .Items.Add methods on the various collections is not really something you can trivially reproduce in LINQ. You can probably do it, but it will be ugly and hard to maintain. What you have is fine. If you want to change it for change's sake, maybe:

RadTreeViewItem parent1 = new RadTreeViewItem {
    Header = NodeHeader(item.Path, item.Name, SelectedPath, ProjectData),
    Tag = item
};
foreach (var child in item.Children)
{
    parent1.Items.Add(new RadTreeViewItem {
        Header = NodeHeader(child.Path, child.Name, SelectedPath, ProjectData),
        Tag = child
    });
}
Parent.Items.Add(parent1);

Not exactly an improvement, IMO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM