如何均匀拆分清单/

时间:2015-04-23 08:57:49

标签: c#

这就是我现在正在做的事情

items = new List<TableItem> ();
            items.Add (new TableItem (){ name = "Apple" });
            items.Add (new TableItem (){ name = "Pear" });
            items.Add (new TableItem (){ name = "Shoe" });
            items.Add (new TableItem (){ name = "Cake" });
            items.Add (new TableItem (){ name = "Vodka" });
            items.Add (new TableItem (){ name = "Alize" });
            items.Add (new TableItem (){ name = "Alizeee" });
            ........
            ........
            ........

这就是我现在正在做的事情,这样一个项目丢失,因为它的计数奇数,列表将从api填充,所以可以有任意数量的项目添加到列表中

            int number = items.Count;
            int number2 = number / 2;

            List<TableItem> firstList = items.GetRange(0, number2);
            List<TableItem> secondList = items.GetRange(number2, number2);


            listView1.Adapter = new HomeScreenAdapter(this, firstList);
            listView2.Adapter = new HomeScreenAdapter (this, secondList);

3 个答案:

答案 0 :(得分:2)

如果计数为奇数,则在第二个列表的长度上加1:

array(4) {
  [0]=>
  string(16) "Helllooooo I'mmm"
  [1]=>
  string(25) "<strong>theeeeee</strong>"
  [2]=>
  string(20) "<em> woooooorrd</em>"
  [3]=>
  string(22) "theeee loooonnngessttt"
}

答案 1 :(得分:0)

如果您期望奇数列表 您应该使用Math.CeilMath.Floor根据您的要求选择中间数字 所以,如果你的清单包含5个元素,那么

number = Math.Ceil(5/2) // will return 3;
number = Math.Floor(5/2) // will return 2

答案 2 :(得分:0)

您可以使用LINQ:

var half = items.Count() / 2;
var firstList = items.Take(half).ToList();
var secondList = items.Skip(half).ToList()