Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Answers


Following code returns last “n” numbers from collection,

_mySamleCollection.Skip(Math.Max(0, _mySamleCollection.Count() - n));

Example with sample Code:

readonly List<int> _mySamleCollection =new List<int>();
 
        public void DisplayLastNFromCollection()
        {
          //return last one number value 144
          var Last1Number = ReturnLastNFromColection(1);
          //return last two numbers 16,144
          var Last2Numbers = ReturnLastNFromColection(2); 
        }
        public IEnumerable<int> ReturnLastNFromColection(int n)
        {
            _mySamleCollection.Add(2);
            _mySamleCollection.Add(4);
            _mySamleCollection.Add(16);
            _mySamleCollection.Add(144);
            return _mySamleCollection.Skip(Math.Max(0, _mySamleCollection.Count() - n));
        }

For detailed explanation please check following Q&A thread...

https://stackoverflow.com/questions/3453274/using-linq-to-get-the-last-n-elements-of-a-collection


Share your answer


Share as a guest

Please subscribe me to the CodeChef4U.

By creating your new answer, you agree to the privacy policy and terms of service.