Mechandrius
Mechandrius

Reputation: 357

Iterate over multiple IEnumerables dynamically (Linq Concat?)

What is the best way to iterate dynamically over multiple IEnumerables at once? The lists are nested in a complex way. It is not a simple List<List<Entity>>

Example of desired behavior:

Dictionary<int, List<Entity>[]> submeshes = new Dictionary<int, List<Entity>[]>();

foreach(Entity e in submeshes.SelectMany(i = 1, i = 4).Select(o => o[0] , o2 => o2[2])).Concat()
{
    e.Update();
}

foreach(Entity e in submeshes.SelectAll().Select(o => o[0])).Concat()
{
    e.Update();
}

The problem is that each submesh consists of different lists and I need two cases.

  1. I need a distinction in the Linq command for a specific mix of lists.
  2. I need to iterate all lists.

Upvotes: 0

Views: 292

Answers (2)

Mechandrius
Mechandrius

Reputation: 357

I ran a performance test and the concat + foreach really was performing bad. ListCombined would be a separate list that contains all lists in one. The fastest way would really be sequencially iterating over list1, list2, etc.. So my final solution would be a method, that run a generic method to invoke the same functions on multiple lists

enter image description here

Upvotes: 0

Rup
Rup

Reputation: 34418

Given

var submeshes = new Dictionary<int, List<Entity>[]>();

i.e. we have a dictionary with values of arrays of lists of entities, and that you just want to extract the entities without e.g. knowing which dictionary entry they came from, I think you can just use two SelectMany()s:

submeshes.Values              // = value collection of arrays of lists of entities
         .SelectMany(a => a)  // = enumerable of lists of entities
         .SelectMany(a => a)  // = enumerable of entities

You can then iterate over the resulting enumerable and it will dynamically stitch together all the source lists as it goes, i.e. there's no copying or materializing into other collections along the way.

Upvotes: 2

Related Questions