Using Linq in C#, how would you query an Object[]
( data
) so that it returns all List<int>
objects in the array and flattens them into a single List<int>
?
This is what I tried, but for some reason it is not working:
List<int> IntData;
IntData = data.Where(n => n.GetType().IsGenericType)
.Where(n => n.GetType().GetGenericTypeDefinition() == typeof(List<int>))
.Select(n => (List<int>) n)
.SelectMany( n => n));
You can use Linq's OfType
method to do this:
List<int> IntData = data.OfType<List<int>>()
.SelectMany(i => i)
.ToList();
You could even make it more generic to accept any IEnumerable<int>
:
List<int> IntData = data.OfType<IEnumerable<int>>()
.SelectMany(i => i)
.ToList();
我现在打电话的编辑能力有限,但我认为这可以满足您的需求:
data.OfType<List<int>>().SelectMany(x=>x).ToList();
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.