C# 列表元素集合
我有一张清单:C# 列表元素集合,c#,linq,list,collections,lambda,C#,Linq,List,Collections,Lambda,我有一张清单: List<string> list = new List<string>(); list.Add("x1"); list.Add("x2"); list.Add("x3"); list.Add("x4"); . . . . list.Add("x100"); List List=新列表(); 列表。添加(“x1”); 列表。添加(“x2”); 列表。添加(“x3”); 列表。添加(“x4”); . . . . 列表。添加(“x100”); 现在我需要一
List<string> list = new List<string>();
list.Add("x1");
list.Add("x2");
list.Add("x3");
list.Add("x4");
.
.
.
.
list.Add("x100");
List List=新列表();
列表。添加(“x1”);
列表。添加(“x2”);
列表。添加(“x3”);
列表。添加(“x4”);
.
.
.
.
列表。添加(“x100”);
现在我需要一个列表集合,其中正好包含listofX中的10个元素
因此,List1有来自listofX的1到10个元素,list2有来自listofX的11到20个元素
这可以通过Lambda表达式或LINQ来实现吗?它可以通过以下方式实现:
var list1 = list.Take(10).ToList();
var list2 = list.Skip(10).Take(10).ToList();
var list3 = list.Skip(20).Take(10).ToList();
等等
或者更一般地说:
var number = list.Count / 10;
var lists = new List<List<string>>(number);
for (int i = 0; i < number; i++)
lists.Add(list.Skip(i * 10).Take(10));
var number=list.Count/10;
var列表=新列表(编号);
for(int i=0;i
这将创建这些列表的列表。类似于:
var lists = Enumerable
.Range(0,10)
.Select(x=>
Enumerable
.Range(x*10+1,10)
.Select(y=>"x" + y.ToString()));
如果你正在寻找一种通用的方法,那么也许
var list=Enumerable.Range(1,100).Select(y=>"x" + y.ToString());
var newlist=Enumerable.Range(0,10).Select(x=>list.Skip(x*10).Take(10));
最后,您可以使用如下扩展方法:
public static IEnumerable<List<T>> InSetsOf<T>(this IEnumerable<T> source, int max)
{
var toReturn = new List<T>(max);
foreach (var item in source)
{
toReturn.Add(item);
if (toReturn.Count == max)
{
yield return toReturn;
toReturn = new List<T>(max);
}
}
if (toReturn.Any())
{
yield return toReturn;
}
}
var newList=list.InSetsOf(10);
您正在寻找的是一种批处理列表的方法,编写IEnumerable扩展来实现这一点相当简单 以下是您可以按原样使用的代码:
public static class Extensions {
public static IEnumerable<IEnumerable<TSource>> BreakIntoChunks<TSource >(this IEnumerable<TSource> source, int size)
{
TSource[] bucket = null;
var count = 0;
foreach (var item in source)
{
if (bucket == null)
{
bucket = new TSource[size];
}
bucket[count++] = item;
// The bucket is fully buffered before it's yielded
if (count != size)
{
continue;
}
// Select is necessary so bucket contents are streamed too
yield return bucket.Select(x => x);
bucket = null;
count = 0;
}
// Return the last bucket with all remaining elements
if (bucket != null && count > 0)
{
yield return bucket.Take(count);
}
}
}
公共静态类扩展{
公共静态IEnumerable细分块(此IEnumerable源,int-size)
{
TSource[]bucket=null;
var计数=0;
foreach(源中的var项)
{
if(bucket==null)
{
bucket=新的TSource[size];
}
桶[count++]=物料;
//铲斗在屈服之前已完全缓冲
如果(计数!=大小)
{
继续;
}
//选择是必要的,因此桶内的内容也会流式传输
收益返回桶。选择(x=>x);
bucket=null;
计数=0;
}
//返回最后一个铲斗和所有剩余的滤芯
if(bucket!=null&&count>0)
{
产量返回桶。取(计数);
}
}
}
使用此方法,您只需调用
list.breakintockuns(10)
//要将10个项目分成一批第二个范围应该是skip和take-Through的组合,因为“x1”可能是一个占位符。如果是占位符,则选择yes。它需要重新修改,我可能会使用不同的方法。非常优雅和简单。不错