The best way to get a count of IEnumerable

前端 未结 11 1424
悲哀的现实
悲哀的现实 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();

提交回复
热议问题