简体   繁体   中英

Nested IEnumerable/Arrays, how to access a deeply nested property

So I have an IEnumerable object that contains a queue(list), each item contains 3 properties. One of those properties ("States") contains another array... and this array contains the property "Messages". Fairly confusing, that's why I took a photo of the local in debugging. 抱歉,我不得不删除敏感数据 Had to edit sensible data out.

I only have this IEnumerable object to work with. How do I reach the property "message"?

I already tried some Lambda expressions... Like

var _message = _criticalData.Select(item1 => item1.States.Select(item2 =>item2.Messages).ToArray()).ToArray()

Then I can create a new array/list of strings and foreach each _message into it.

Atleast I think it works (can't test it at home). But it would also be really really slow. Is there any other way to do this?

You have to flatten out multiple lists, so use SelectMany like:

string[] output = _criticalData.SelectMany(outer => 
                            outer.States.SelectMany(inner => inner.Messages))
                            .ToArray();

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