Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I traverse this list in this manner?

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...

like image 534
markzzz Avatar asked Nov 15 '12 10:11

markzzz


People also ask

What do you mean by traversing a list?

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.

How can we traverse the elements of list in Python?

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.

How do you use traverse in Python?

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.


2 Answers

Yes, with a group by:

foreach (var group in items.GroupBy(i => i.ID))
{
    foreach (var item in group)
    {
    } 
}
like image 194
Amiram Korach Avatar answered Oct 05 '22 20:10

Amiram Korach


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)
    {
        // ...
    } 
}
like image 42
Tim Schmelter Avatar answered Oct 05 '22 20:10

Tim Schmelter