日期:2014-05-18  浏览次数:20899 次

请问List查询
List<int> li = new List<int>{0,1,5,3,8};

怎么获取前三个元素到新的集合,能不能用一句

------解决方案--------------------
C# code
            List<int> li = new List<int> { 0, 1, 5, 3, 8 };
            List<int> newlist = li.Take(3).ToList();

------解决方案--------------------
C# code
or
            List<int> li = new List<int> { 0, 1, 5, 3, 8 };
            List<int> newlist = new List<int>();
            for (int i = 0; i < li.Count; i++)
            {
                if (i < 3)
                    newlist.Add(li[i]);
            }

------解决方案--------------------
LINQ语句Take
C# code

var result = li.Take(3);

------解决方案--------------------
List<int> li = new List<int> { 0, 1, 5, 3, 8 }; 
List<int> newlist = new List<int>(); 
for (int i = 0; i < li.Count; i++) { if (i < 3) newlist.Add(li[i]); }
------解决方案--------------------
用一句 来实现
那么LINQ是最优雅的了:

List<int> li = new List<int>{0,1,5,3,8};
li=li.Take(3).ToList();
------解决方案--------------------
探讨
C# code

List<int> li = new List<int> { 0, 1, 5, 3, 8 };
List<int> newlist = li.Take(3).ToList();

------解决方案--------------------
LZ,我还可以再复制一遍么
var newLi=li.Take(3).ToList();
------解决方案--------------------
学习了。路过
------解决方案--------------------
顶顶~~
------解决方案--------------------
这个思路很清晰。便于理解
探讨

C# code
or
List<int> li = new List<int> { 0, 1, 5, 3, 8 };
List<int> newlist = new List<int>();
for (int i = 0; i < li.Count; i++)
{
i……

------解决方案--------------------
探讨

LZ,我还可以再复制一遍么
var newLi=li.Take(3).ToList();