The best way to get a count of IEnumerable

前端 未结 11 1400
悲哀的现实
悲哀的现实 2020-12-14 15:47

Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection?

Possible with LIN

11条回答
  •  -上瘾入骨i
    2020-12-14 16:26

    Not possible with LINQ, as calling .Count(...) does enumerate the collection. If you're running into the problem where you can't iterate through a collection twice, try this:

    List myList = dataContext.MyTable.ToList();
    int myTableCount = myList.Count;
    
    foreach (MyTableItem in myList)
    {
       ...
    }
    

提交回复
热议问题