我试图达到同样的效果,这个问题问:我如何排序列表分为2分或多个列
I want to show list items as 2 or more columns (dynamic alignment)
除此之外,而不需要脚本或CSS黑客,我会喜欢重新排序数据以便我可以使用“float:left;”
所以不是列表回来像1,2,3,4,5,6,7,8,9,10
为两列,将回来1,6,2,7, 3,8,4,9,5,10
可能吗?
我试图达到同样的效果,这个问题问:我如何排序列表分为2分或多个列
I want to show list items as 2 or more columns (dynamic alignment)
除此之外,而不需要脚本或CSS黑客,我会喜欢重新排序数据以便我可以使用“float:left;”
所以不是列表回来像1,2,3,4,5,6,7,8,9,10
为两列,将回来1,6,2,7, 3,8,4,9,5,10
可能吗?
这里有一种方法,使用LINQ:
var m = (int)Math.Ceiling(input.Count()/2d); // two columns
var sorted = input.Select((x, i) => new { x, i })
.OrderBy(p => p.i % m)
.Select(p => p.x);
这可以相当容易地推广到任意数量的列。如果你愿意,它可以很容易地变成一个扩展方法:
public static IEnumerable<T> Columns<T>(this IEnumerable<T> input, int cols)
{
if (cols < 1)
{
throw new ArgumentOutOfRangeException(...);
}
var m = (int)Math.Ceiling(input.Count()/(double)cols);
return input.Select((x, i) => new { x, i })
.OrderBy(p => p.i % m)
.Select(p => p.x);
}
// Usage
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var sorted = input.Columns(2); // { 1, 6, 2, 7, 3, 8, 4, 9, 5, 10 }
这将很容易地覆盖两列。
public static IEnumerable<T> UseTwoColumns<T>(List<T> list)
{
int halfway = list.Count/2;
for (int i = 0; i < halfway; i++)
{
yield return list[i];
yield return list[halfway + i];
}
if (list.Count % 2 != 0)
yield return list[list.Count - 1];
}
如果你想把它推广到路过的列数作为参数,它会是一个稍微更复杂:
public static IEnumerable<T> UseColumns<T>(List<T> list, int columns)
{
int columnHeight = list.Count/columns;
for (int i = 0; i < columnHeight + 1; i++)
{
for (int j = 0; j < columns; j++)
{
int index = i + columnHeight * j;
if (index < list.Count)
yield return list[index];
}
}
}
也许像'的OrderBy(行=> row.ColumnOne).ThenBy(行=> row.ColumnTwo)' –