84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
访问接口返回数据类型为List<List<model>>,现在想将其中的model插入数据库,感觉一点点循环有点傻,0.0...,各位有没有其他的方法?
认证高级PHP讲师
C# words:
var flat = list.SelectMany(l=>l).ToList();
Java words:
List<model> flat = list.stream().flatMap(List::stream).collect(Collectors.toList());
list.stream().flatMap(model-> model.stream()).forEach(System.out::println);
The data structure dictates, let’s loop
public static IEnumerable<T> GetItems<T>(this List<List<T>> list) { foreach (var child in list) { foreach (var item in child) { yield return item; } } } public static IEnumerable<T> GetNestItems<T>(this System.Collections.IList list) { Type type = null; foreach (var item in list) { if (type == null) type = item.GetType(); if (type == typeof(T)) { yield return (T)item; } else if (type.GetGenericTypeDefinition() == typeof(List<>)) { var items = GetNestItems<T>((System.Collections.IList)item); foreach (var t in items) { yield return t; } } } }
Don’t cycle yourself. Or catch other functions to help you complete the loop.
C# words:
Java words:
list.stream().flatMap(model-> model.stream()).forEach(System.out::println);
The data structure dictates, let’s loop
Don’t cycle yourself. Or catch other functions to help you complete the loop.