I have a list of objects that looks like this :
ID:2000
Title:"Title 1"
Description:"My name is Marco"
ID:2000
Title:"Title 2"
Description:"My name is Luca"
ID:3000
Title:"Title 3"
Description:"My name is Paul"
ID:4000
Title:"Title 4"
Description:"My name is Anthony"
ID:4000
Title:"Title 5"
Description:"My name is Carl"
ID:4000
Title:"Title 6"
Description:"My name is Jadett"
now, I'd like to browse (traverse) it with a for each. But I want to traverse it starting from the same ID. So, first a foreach for the single/unique ID (2000, 3000, 4000, so 3 steps). Than, for each "ID" step, each Title/Description: so 2 steps for the ID 2000, 1 for the ID 3000 and 3 for the ID 4000. List is ordered by ID.
How can I do it? Group by? Uhm...
Traversing is the most common operation that is performed in almost every scenario of singly linked list. Traversing means visiting each node of the list once in order to perform some operation on that.
The for loop, is frequently used for iterating elements of a list, while loop on the other hand, is capable of serving several purposes, and it can iterate a list too! The logic is pretty much similar for accessing an element using indices. Run the loop from 0 to len(myList) and simply access the elements.
You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially. To use this method, provide the starting and ending indices along with a step value and then traverse the string.
Yes, with a group by:
foreach (var group in items.GroupBy(i => i.ID))
{
foreach (var item in group)
{
}
}
Yes, you can use GroupBy
.
first the groups itself:
var idGroups = items.GroupBy(i => i.ID).ToList(); // omit ToList() if scalability is more important than performance since it creates a new list but doesn't enables to enumerate the result multiple times without querying again
foreach(var idGroup in idGroups)
{
// ...
}
then all items of each group:
foreach (var idGroup in idGroups)
{
foreach (var item in idGroup)
{
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With