The best way to get a count of IEnumerable

前端 未结 11 1397
悲哀的现实
悲哀的现实 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条回答
  • 2020-12-14 16:26

    An IEnumerable will have to iterate through every item. to get the full count. If you just need to check if there is one or more items in an IEnumerable a more efficient method is to check if there are any. Any() only check to see there is a value and does not loop through everything.

    IEnumerable myStrings = new List(){"one","two", "three"};

    bool hasValues = myStrings.Any();

    0 讨论(0)
  • 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<MyTableItem> myList = dataContext.MyTable.ToList();
    int myTableCount = myList.Count;
    
    foreach (MyTableItem in myList)
    {
       ...
    }
    
    0 讨论(0)
  • 2020-12-14 16:28

    Use this.

    IEnumerable list =..........;
    
    list.OfType<T>().Count()
    

    it will return the count.

    0 讨论(0)
  • 2020-12-14 16:30

    You will have to enumerate to get a count. Other constructs like the List keep a running count.

    0 讨论(0)
  • 2020-12-14 16:30

    In any case, you have to loop through it. Linq offers the Count method:

    var result = myenum.Count();
    
    0 讨论(0)
提交回复
热议问题