訪問接口返回數(shù)據(jù)類型為List<List<model>>,現(xiàn)在想將其中的model插入數(shù)據(jù)庫,感覺一點點循環(huán)有點傻,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);
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.