var balls = new List<ball>() { new ball() {Id=1,color="red" }, new ball() {Id=2,color="red" }, new ball() {Id=3,color="red" }, new ball() {Id=4,color="green" }, new ball() {Id=5,color="green" }, new ball() {Id=6,color="green" }, new ball() {Id=7,color="black" }, new ball() {Id=8,color="black" }, new ball() {Id=9,color="black" } }; //怎么样将balls排序成result?? var result = new List<ball>() { new ball() {Id=1,color="red" }, new ball() {Id=4,color="green" }, new ball() {Id=7,color="black" }, new ball() {Id=2,color="red" }, new ball() {Id=5,color="green" }, new ball() {Id=8,color="black" }, new ball() {Id=3,color="red" }, new ball() {Id=6,color="green" }, new ball() {Id=9,color="black" }, };
只想到了个笨方法
var r = (from b in balls where b.color == "red" orderby b.Id select b).ToList() ; var g = (from b in balls where b.color == "green" orderby b.Id select b).ToList() ; var k = (from b in balls where b.color == "black" orderby b.Id select b).ToList() ; List<ball> result = new List<ball>(); for (int i = 0; i < r.Count; i++) { result.Add(r[i]); result.Add(g[i]); result.Add(k[i]); }
这肯定不行,实际情况颜色不确定,各颜色数量不确定怎么办。
@丶飘零丶:
太丑,将就看下吧
var balls = new List<ball>() { new ball() {Id=1,color="red" }, new ball() {Id=2,color="red" }, new ball() {Id=3,color="red" }, new ball() {Id=4,color="green" }, new ball() {Id=5,color="green" }, new ball() {Id=6,color="green" }, //new ball() {Id=7,color="black" }, //new ball() {Id=8,color="black" }, new ball() {Id=9,color="black" } }; var c = (from b in balls group b.color by b.color into g select g.Key).ToList(); List<List<ball>> colorList = new List<List<ball>>(); foreach (var cc in c) { colorList.Add((from b in balls where b.color == cc.ToString() select b).ToList()); } int maxLength = 0; foreach (var n in colorList) { if (n.Count > maxLength) { maxLength = n.Count; } } List<ball> result = new List<ball>(); for (int i = 0; i < maxLength; i++) { for (int j = 0; j < c.Count; j++) { if (i < colorList[j].Count) { result.Add(colorList[j][i]); } } }
@plcly: 这个依然不能解决当同一色的太多的时候尾数的问题。
@丶飘零丶: 这个我已经去掉了最后两个排序了,结果是1492536,你需要的结果是什么,不如你提供一个复杂的,用这段程序试一下,哪里不一样
@plcly:
var balls = new List<Ball>() { new Ball() {Id=1,color="red" }, new Ball() {Id=2,color="red" }, new Ball() {Id=3,color="red" }, new Ball() {Id=3,color="red" }, new Ball() {Id=3,color="red" }, new Ball() {Id=3,color="red" }, new Ball() {Id=3,color="red" }, new Ball() {Id=4,color="black" }, new Ball() {Id=5,color="black" }, new Ball() {Id=6,color="black" }, new Ball() {Id=7,color="green" }, new Ball() {Id=8,color="green" }, new Ball() {Id=9,color="green" } };
假如我一种色很多的话,就有问题了
先获取原表中同一颜色的数量colorCount 你这里是3
循环抽取数据组成新表,规律是:
两层嵌套循环
int ballsIndex=0;
for(int i=0;i<colorCount;i++)
{
for(int j = i;j<balls.Count;j+= colorCount)
{
result[j]=balls[ballsIndex];
ballsIndex++;
}
}