1

我正在尝试达到与此问题相同的结果:

我想将列表项显示为 2 列或更多列(动态对齐)

除了需要脚本或 css hack 之外,我想重新排序数据以开始,以便我可以使用“float:left;”

因此,而不是像 1,2,3,4,5,6,7,8,9,10 这样返回的列表

对于两列,它将返回 1,6,2,7,3,8,4,9,5,10

可能的?

4

2 回答 2

4

这是使用 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 }
于 2013-05-30T18:40:51.080 回答
1

这将很容易覆盖两列。

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];
        }
    }
}
于 2013-05-30T18:36:59.730 回答