Reputation: 2249
I have a treenode collection as IEnumerable<treenode>
nodes. Is there any method to create a collection of treenode.guid
directly from nodes without iterating all the elements?
E.g.:
guidcollection nodeguids = nodes.somemethod();
Upvotes: 0
Views: 69
Reputation: 56688
The answer is not - you obviously need to iterate through the collection of nodes if you need some info from each of them. However you can do something like:
IEnumerable<Guid> nodeguids = nodes.Select(n => n.Id);
This way you do not perform an iteration manually at least. Although implementation of Select
involves iteration over all the elements of the collection, and it will be done at the moment you will try to use the nodeguids
collection somewhere.
Upvotes: 3
Reputation: 19583
LINQ uses a lazy iterator. So you can create a collection like this...
IEnumerable<TreeNode> myCollection = GetTreeNodes();
IEnumerable<Guid> guidCollection = myCollection.Select(tn => tn.Guid);
The guidCollection will not be populated until it is iterated, counted, acted upon in some way.
You could also just go old school.
function IEnumerable<Guid> GetIdsFromCollection(TreeNode collection)
{
foreach (var item in collection)
yield return item;
}
Upvotes: 0